﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using WhiteBoard;
using LumiSoft.Net.UDP;
using LumiSoft.Net.Codec;
using WinSound.Media.Wave;

namespace WFFS
{
    public partial class Form1 : Form
    {
        private static string SQLCONNSTR = System.Configuration.ConfigurationManager.AppSettings["connectionstring"];
        public static SqlConnection dbConnect;
        //delegate void MsgRef(string msg);
        //AsySocket listener = null;
        //SortedList<string, AsySocket> clients = new SortedList<string, AsySocket>();
        private AsySocket socket = null;
        delegate void CallBackRef(string msg);
        private string clientname;
        public NetworkManager socketnetWork;

        public Form1()
        {  
            
            InitializeComponent();
            initForm();  //李万峰            
            FormInit();//肖军
            InitAudio(); //冯曦
        }

        //窗口最大化与正常情况的切换
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                //方便测试用
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                this.KeyPreview = false;
                this.ShowInTaskbar = true;
                this.ControlBox = true;
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                //this.WindowState = FormWindowState.Maximized;
                this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
                this.BackColor = System.Drawing.Color.Black;
                //this.ClientSize = new System.Drawing.Size(1920, 1080);
                this.ControlBox = false;
                //this.Controls.AddRange(new System.Windows.Forms.Control[] { this.picture1, this.word });
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                this.KeyPreview = true;
                this.MaximizeBox = false;
                this.Name = "screen";
                this.ShowInTaskbar = false;
                this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
                this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            }
        }

        #region 李万峰代码
        //////////////////////////////////李万峰代码//////////////////////////////////////////////

        //定义窗体级公用变量 
        public string role = ConfigurationManager.AppSettings["role"];//当前平板的角色
        DShapeList drawingList = new DShapeList();							//图元
        DShapeList drawingListUndo = new DShapeList();						//撤销图形保存
        public String path;//图片背景
        //临时变量
        private GraphicsPath mousePath;
        Point startPoint, endPoint; //开始画线的起点坐标，此变量的值将在MOUSEDOWN事件中确定 
        public Color drawColor = Color.FromArgb(0, 0, 0);//选择的颜色
        public int lineWidth = 4;//线宽度
        private ImageType newType = ImageType.Empt;
        //表单初始化
        public void initForm()
        {
            this.Drawing.Paint += new System.Windows.Forms.PaintEventHandler(this.Drawing_Paint);
            //控件要能拖动必须设置控件的AllowDrop=true
            this.Drawing.AllowDrop = true;
           // this.a.AllowDrop = true;
           // this.b.AllowDrop = true;
           // this.c.AllowDrop = true;
            // 这句代码就是说在这个类中我们不检查跨线程的调用是否合法
            Control.CheckForIllegalCrossThreadCalls = false;
            if (role.Equals("1"))
            {
                //画图
                this.Drawing.MouseDown += new MouseEventHandler(Drawing_MouseDown);
                this.Drawing.MouseMove += new MouseEventHandler(Drawing_MouseMove);
                this.Drawing.MouseUp += new MouseEventHandler(Drawing_MouseUp);
                //拖拽
                //  this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
                this.Drawing.DragDrop += new System.Windows.Forms.DragEventHandler(this.Drawing_DragDrop);
                this.Drawing.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drawing_DragEnter);
            }
            else if (role.Equals("2"))
            {
                panelPaint.Visible = false;
            }

        }
        //设置线的宽度
        private void setlineWidth(object sender, EventArgs e)
        {
            if (this.comboBox1.Text != null)
            {
                setlineWidth(this.comboBox1.Text);
                SetPen(this.drawColor, this.lineWidth);
            }
        }
        /// <summary>
        /// 设置线宽
        /// </summary>
        /// <param name="text"></param>
        private void setlineWidth(String text)
        {
            lineWidth = int.Parse(text);
        }
       
        /// <summary>
        /// 画图事件
        /// </summary>		
        private void Drawing_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics displayGraphics = e.Graphics;
            //Graphics displayGraphics=this.Drawing.CreateGraphics();
            switch (newType)
            {
                case ImageType.Path:
                    if (mousePath != null)
                    {
                        displayGraphics.DrawPath(new Pen(drawColor, lineWidth), mousePath);
                    }
                    break;
                case ImageType.Pick:
                    break;
            }
            drawingList.DrawList(displayGraphics);
        }

        //设置画图风格
        public void SetPen(Color drawColor, int lineWidth)
        {
            whenSetPen(drawColor, lineWidth);
            if (netWork != null)
            {
                WBMsgDrawStyle drawStyle = new WBMsgDrawStyle();
                drawStyle.drawColor = drawColor;
                drawStyle.lineWidth = lineWidth;
                netWork.SendWBMsgConnectedHdlr(drawStyle);
            }
        }

        //当设置画图风格
        public void whenSetPen(Color drawColor, int lineWidth)
        {
            this.drawColor = drawColor;
            this.lineWidth = lineWidth;
        }
        //清除显示
        public void clearScreen()
        {
            drawingList = new DShapeList();
            drawingListUndo = new DShapeList();
            //清除控件           
            List<Control> list = new List<Control>();
            foreach (Control Item in this.Drawing.Controls)
            {
                list.Add(Item);
            }
            int size = this.Drawing.Controls.Count;
            for (int i = 0; i < size; i++)
            {
                this.Drawing.Controls.Remove(list[i]);
            }
            Drawing.Invalidate();
        }
        //画图，当鼠标按下
        public void WhenMouseDown(Point pt)
        {
            //鼠标按下确定起点的坐标，把这个变量赋于STARTPOINT值 
            startPoint = pt;
            newType = ImageType.Path;
            switch (newType)
            {
                case ImageType.Path:
                    mousePath = new GraphicsPath();
                    mousePath.AddLine(pt, pt);
                    break;
            }
        }
        //画图，当鼠标移动
        public void WhenMouseMove(Point pt)
        {
            switch (newType)
            {
                case ImageType.Path:
                    mousePath.AddLine(pt, pt);
                    break;
            }
            Drawing.Invalidate();
        }
        //画图，当鼠标抬起
        public void WhenMouseUp(Point pt)
        {
            endPoint = pt;
            switch (newType)
            {
                case ImageType.Path:
                    drawingList.Add(new DPath(mousePath, drawColor, lineWidth));
                    mousePath = null;
                    break;
            }
            newType = ImageType.Text;
            Drawing.Invalidate();
        }
        //画图，撤消
        public void WhenBack()
        {
            if (drawingList.Count == 0)
                return;
            drawingListUndo.Add(drawingList[drawingList.Count - 1]);
            drawingList.RemoveAt(drawingList.Count - 1);
            Drawing.Invalidate();
        }
        //画图，恢复
        public void WhenProceed()
        {
            if (drawingListUndo.Count == 0)
                return;
            drawingList.Add(drawingListUndo[drawingListUndo.Count - 1]);
            drawingListUndo.RemoveAt(drawingListUndo.Count - 1);
            Drawing.Invalidate();
        }
        private void Drawing_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                WhenMouseDown(new Point(e.X, e.Y));
                WhenMouseSentToPeers("down", new Point(e.X, e.Y));

            }
        }

        private void Drawing_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                switch (newType)
                {
                    case ImageType.Path:
                        WhenMouseMove(new Point(e.X, e.Y));
                        WhenMouseSentToPeers("move", new Point(e.X, e.Y));
                        break;
                }

            }
        }
        private void Drawing_MouseUp(object sender, MouseEventArgs e)
        {
            switch (newType)
            {
                case ImageType.Path:
                    WhenMouseUp(new Point(e.X, e.Y));
                    WhenMouseSentToPeers("up", new Point(e.X, e.Y));
                    break;
            }

        }
        /// <summary>
        /// 颜色。
        /// </summary>		
        private void Black_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.Black.BackColor;
            drawColor = this.Black.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void White_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.White.BackColor;
            drawColor = this.White.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void Red_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.Red.BackColor;
            drawColor = this.Red.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void blue_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.blue.BackColor;
            drawColor = this.blue.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void Yellow_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.Yellow.BackColor;
            drawColor = this.Yellow.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void LawnGreen_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.LawnGreen.BackColor;
            drawColor = this.LawnGreen.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void Cyan_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.Cyan.BackColor;
            drawColor = this.Cyan.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void Magenta_Click(object sender, System.EventArgs e)
        {
            this.btnColor.BackColor = this.Magenta.BackColor;
            drawColor = this.Magenta.BackColor;
            SetPen(drawColor, this.lineWidth);
        }

        private void MoreColor_Click(object sender, System.EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                drawColor = colorDialog.Color;
                SetPen(drawColor, this.lineWidth);
            }
        }

        /// <summary>
        /// 后退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_Click(object sender, EventArgs e)
        {
            WhenBack();
            if (netWork != null)
            {
                WBMsgBack wBMsgBack = new WBMsgBack();
                netWork.SendWBMsgConnectedHdlr(wBMsgBack);
            }
        }
        /// <summary>
        /// 前进
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void proceed_Click(object sender, EventArgs e)
        {
            WhenProceed();
            if (netWork != null)
            {
                WBMsgProceed wBMsgProceed = new WBMsgProceed();
                netWork.SendWBMsgConnectedHdlr(wBMsgProceed);
            }
        }
        //设置图片
        private void setImage(String path)
        {
            whenSetImage(path);
            if (netWork != null)
            {
                WBMsgDrawingImage wBMsgDrawingImage = new WBMsgDrawingImage();
                wBMsgDrawingImage.path = path;
                netWork.SendWBMsgConnectedHdlr(wBMsgDrawingImage);
            }

        }

        public void whenSetImage(String path)
        {
            this.path = path;
            this.Drawing.Image = new Bitmap(Application.StartupPath + "\\" + path);
        }

        private void carDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            newType = ImageType.carDrafting;
            Control control = (Control)sender;
            UiDrafting_MouseDown(control.Text, control.Name.Split(',')[0]);

        }
        //图片按下事件
        private void imageDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            newType = ImageType.carDrafting;
            PictureBox pictureBox = (PictureBox)sender;
            UiDrafting_MouseDown(pictureBox.Name, "imgOrder");
        }
        private void Drawing_DragDrop(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                Control control = (Control)sender;
                String text = e.Data.GetData(DataFormats.Text).ToString();
                Point p = control.PointToClient(Control.MousePosition); //点P是相对于画图控件坐标
                Random ran = new Random();
                int RandKey = ran.Next(100, 999);
                string name = "bushu" + RandKey;
                UiDraftingControl_DragDrop(name, text, p);
                if (netWork != null)
                {
                    Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                    WBMsgUiDrafting_DragDrop uiDrafting_DragDrop = new WBMsgUiDrafting_DragDrop();
                    uiDrafting_DragDrop.name = name;
                    uiDrafting_DragDrop.text = text;
                    uiDrafting_DragDrop.p = tm;
                    netWork.SendWBMsgConnectedHdlr(uiDrafting_DragDrop);
                }
            }
        }
        private void Drawing_DragEnter(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                UiDraftingControl_DragEnter(e);
            }
        }
        /////////////////////////////////////////////控件拖动<将控件拖动到另一个容器内>//////////////////////////////////////////////////
        //拖放事件
        //名称 说明
        //DragEnter 当用户在拖放操作过程中首次将鼠标光标拖到控件上时，会引发该事件
        //DragDrop 在完成拖放操作时发生
        //GiveFeedback 在执行拖动操作期间发生
        //DragLeave 如果用户移出一个窗口，则引发DragLeave事件
        //DragOver 如果鼠标移动但停留在同一个控件中，则引发DragOver事件
        //QueryContinueDrag 在拖放操作过程中，当键盘或鼠标按钮状态发生变化时，会引发QueryContinueDrag 事件。QueryContinueDrag事件允许拖动源确定是否应取消拖放操作

        //要拖动的控件的 MouseDown事件
        public void UiDrafting_MouseDown(String title, String type)
        {
            this.back.DoDragDrop(title + "," + type, DragDropEffects.Copy);
            /**
           public DragDropEffects DoDragDrop ( Object sender,DragDropEffects allowedEffects)
           data：用户所要拖动的数据内容。必须将所要拖动的内容传入到这个方法的第一个参数位置。
           allowedEffects：DragDropEffects枚举值之一，此类型包含了拖动操作的效果。DragDropEffects枚举值如表32.8所示。
           DragDropEffects枚举值：
             枚举值 说明
             All 从拖动源复制、移除数据，并将其滚动到放置目标中
             Copy 将数据复制到放置目标
             Link 将拖动源中的数据链接到放置目标
             Move 将拖动源的数据移动到放置目标
             None 放置目标不接受该数据
             Scroll 即将在放置目标中开始滚动，或当前正在滚动
           开发人员在使用DoDragDrop方法时，必须指定参数allowedEffects为表中的任何一个成员，另外，还可以使用位运算符，把其中的任何一个成员作为一个完整参数传入，以得到所需的拖动效果，实现关键代码如下：
             DragDropEffects.Copy| DragDropEffects.None**/
        }
        //控件拖动到控件的 DragEnter事件
        public void UiDraftingControl_DragEnter(DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }


        //声明委托类型
        public delegate void InvokeDele(String name, String text, Point p);
        //控件拖动到控件的 DragDrop事件
        public void UiDraftingControl_DragDrop(String name, String text, Point p)
        {
            //跨线程的控件操作，需要使用委托
            if (this.InvokeRequired)
            {
                //实例化委托
                InvokeDele id = new InvokeDele(this.UiDraftingControl_DragDrop);
                this.Invoke(id, new object[] { name, text, p });
                return;
            }
            Control control = this.Drawing;
            // 取得被拖放的项       
            Button tuttontemp = new Button();
            tuttontemp.Name = name;
            tuttontemp.TextAlign = ContentAlignment.BottomCenter;
            tuttontemp.BackgroundImageLayout = ImageLayout.Center;
            if ((text.Split(','))[1].Equals("car"))
            {

                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\car3.png");
                tuttontemp.Text = (text.Split(','))[0];
            }
            else if ((text.Split(','))[1].Equals("imgOrder"))
            {
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\" + (text.Split(','))[0] + ".jpg");
            }
            else
            {

                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\001.png");
                tuttontemp.Text = (text.Split(','))[0];
            }



            tuttontemp.Location = p;
            control.Controls.Add(tuttontemp);
            tuttontemp.Size = tuttontemp.BackgroundImage.Size;
            tuttontemp.AllowDrop = true;
            if (role.Equals("1"))
            {
                tuttontemp.MouseDown += new MouseEventHandler(UiMove_MouseDown);
                tuttontemp.MouseMove += new MouseEventHandler(UiMove_MouseMove);
                tuttontemp.MouseUp += new MouseEventHandler(UiMove_MouseUp);
            }
        }
        /////////////////////////////////////////////控件移动<控件在对应的容器内移动>//////////////////////////////////////////////////
        //
        bool bDragging = false;//是否移动的变量
        Point mouse_offset;//开始位置
        private void UiMove_MouseDown(object sender, MouseEventArgs e)
        {
            whenUiMove_MouseDown(new Point(-e.X, -e.Y));
            if (netWork != null)
            {
                Point p = new Point(-e.X, -e.Y);
                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                WBMsgUiMove_MouseDown msgUiMove_MouseDown = new WBMsgUiMove_MouseDown();
                msgUiMove_MouseDown.p = tm;
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseDown);
            }
        }
        public void whenUiMove_MouseDown(Point p)
        {
            bDragging = true;
            mouse_offset = p;
        }
        private void UiMove_MouseMove(object sender, MouseEventArgs e)
        {
            String name = ((Control)sender).Name;
            //设置拖动时鼠标箭头
            ((Control)sender).Cursor = Cursors.Arrow;
            whenUiMove_MouseMove(name, e.Button, Control.MousePosition);
            if (netWork != null)
            {
                Point p = Control.MousePosition;
                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                WBMsgUiMove_MouseMove msgUiMove_MouseMove = new WBMsgUiMove_MouseMove();
                msgUiMove_MouseMove.name = name;
                msgUiMove_MouseMove.button = e.Button;
                msgUiMove_MouseMove.mousePos = tm;
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseMove);
            }
        }
        public void whenUiMove_MouseMove(String name, MouseButtons button, Point mousePos)
        {
            if (button == MouseButtons.Left && bDragging)
            {
                mousePos.Offset(mouse_offset.X, mouse_offset.Y);//设置偏移
                Control control = GetControl(name, this.Drawing);
                if (control == null) return;
                control.Location = control.Parent.PointToClient(mousePos);
            }
        }
        //根据名字得到控件
        private Control GetControl(string name, Control parent)
        {
            foreach (Control Item in parent.Controls)
            {
                if (Item.Name == name)
                {
                    return Item;
                }
                else
                {
                    Control control = GetControl(name, Item);
                    if (control != null)
                    {
                        return control;
                    }
                }
            }
            return null;
        }
        private void UiMove_MouseUp(object sender, MouseEventArgs e)
        {
            whenUiMove_MouseUp();
            if (netWork != null)
            {
                WBMsgUiMove_MouseUp msgUiMove_MouseUp = new WBMsgUiMove_MouseUp();
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseUp);
            }
        }
        public void whenUiMove_MouseUp()
        {
            bDragging = false;
        }
        ////////////////////////////////////////////////////////网络传输通讯////////////////////
        public NetworkManager netWork;
        /// <summary>
        /// 拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void zhengcha_Click(object sender, EventArgs e)
        {
             Camera cm = new Camera();
              cm.form = this;
               cm.Owner = this;
               cm.Focus();
              cm.Show();

        }
        //侦查上传图片
        public void whenUploadImage(byte[] byteArrayIn, String name)
        {
            if (!byteArrayIn.Length.Equals(0))
            {
                string path = Application.StartupPath;
                path += "\\pic\\" + name;
                MemoryStream MS = new MemoryStream(byteArrayIn);
                Bitmap image = new System.Drawing.Bitmap(MS);
                this.Drawing.Image = image;
                image.Save(path);
            }
        }
        /// <summary>
        /// 设置soket的连接状态
        /// </summary>
        /// <param name="StrText"></param>
        /// <param name="StrWaveFileName"></param>
        public void SetMusicalStatus(String type, string state)
        {

            if (this.netWork != null)
            {
                if (type.Equals("stop"))
                {
                    switch (netWork.soketType)
                    {
                        case SOKET_TYPE.enClientMode:
                            //如果为客户端模式，更改客户端的连接状态
                            this.soketState.Text = state;
                            this.netWork = null;
                            break;

                    }
                }
                else
                {
                    switch (netWork.soketType)
                    {
                        case SOKET_TYPE.enClientMode:
                            //如果为客户端模式，更改客户端的连接状态
                             this.soketState.Text = state;
                            break;

                    }
                }
            }
        }
        //画图时对应的发送信息
        public void WhenMouseSentToPeers(String type, Point p)
        {
            if (netWork != null)
            {

                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                switch (type)
                {
                    case "down":
                        WBMsgDrawMouseDown Msgbegin = new WBMsgDrawMouseDown();
                        Msgbegin.startPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(Msgbegin);
                        break;
                    case "move":
                        WBMsgDrawMouseMove MsgLine = new WBMsgDrawMouseMove();
                        MsgLine.movPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(MsgLine);
                        break;
                    case "up":
                        WBMsgDrawMouseUp Msgend = new WBMsgDrawMouseUp();
                        Msgend.endPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(Msgend);
                        break;
                    default:
                        break;
                }
            }
        }
        //启动
        private void startNetwork(object sender, EventArgs e)
        {
            if (netWork == null)
            {
                netWork = new NetworkManager(this, ConfigurationManager.AppSettings["whiteboard_serverIP"], ConfigurationManager.AppSettings["whiteboard_serverPort"], SOKET_TYPE.enServerMode);
                netWork.StartListening();
                // MessageBox.Show("成功启动");
           //     button4.Text = "停止";
            }
            else
            {
                netWork.Disconnect();
                netWork = null;
              //  button4.Text = "启动";
            }
        }
        //连接
        private void connectNetwork(object sender, EventArgs e)
        {
            string ip = ConfigurationManager.AppSettings["whiteboard_serverIP"];
            string port = ConfigurationManager.AppSettings["whiteboard_serverPort"];
            if (netWork == null)
            {
                netWork = new NetworkManager
                    (
                    this, ip, port, SOKET_TYPE.enClientMode
                    );
                netWork.ConnectToListeningServer();
            }

        }
        //清除
        private void clearScreen(object sender, EventArgs e)
        {
            this.clearScreen();
            if (netWork != null)
            {
                WBMsgClearScreen screen = new WBMsgClearScreen();
                netWork.SendWBMsgConnectedHdlr(screen);
            }
        }

        private void stopSoket(object sender, EventArgs e)
        {
            if (netWork != null)
            {
                netWork.Disconnect();
            }
        }

        #endregion

        #region 肖军

        private void FormInit()
        {
            dbConnect = new SqlConnection();
            dbConnect = SqlConnection();
           
            panelLV.Visible = false;
            //panelInfo.Visible = false;
            
            this.timerInfo.Interval = 500;

            //文字命令
            //监听
            panelOrder.Visible = false;
            clientname = ConfigurationManager.AppSettings["ClientName"];
            //客户端连接
            //string ip = ConfigurationManager.AppSettings["whiteboard_serverIP"];
            //string port = ConfigurationManager.AppSettings["order_serverPort"];
            //if (socketnetWork == null)
            //{
            //    socketnetWork = new NetworkManager
            //        (
            //        this, ip, port, SOKET_TYPE.enClientMode
            //        );
            //    socketnetWork.ConnectToListeningServer();
            //}

            //连接
            InfoConnectServer();
        }
        #region old

        void socket_OnClosed(string SocketID, string ErrorMessage)
        {
            //服务器关闭
            //--old
            //MessageBox.Show(this, "服务器关闭");
            //this.Close();
            //--

            //启动Timer去主动连接服务器
            InfoConnectServer();
            //this.timerInfo.Start();
            
        }

        //定义连接服务器
        private void timerInfo_Tick(object sender, EventArgs e)
        {
            InfoConnectServer();
        }
        //
        private bool InfoConnectServer()
        {
            string ip = ConfigurationManager.AppSettings["whiteboard_serverIP"];
            string port = ConfigurationManager.AppSettings["order_serverPort"];            
            string LocalIP = ConfigurationManager.AppSettings["localIP"];
            //连接
            socket = new AsySocket(LocalIP, 0);
            socket.OnSended += new AsySocketEventHandler(socket_OnSended);
            socket.OnSendTo += new AsySocketEventHandler(socket_OnSendTo);
            socket.OnStringDataAccept += new StringDataAcceptHandler(socket_OnStringDataAccept);
            socket.OnClosed += new AsySocketClosedEventHandler(socket_OnClosed);
            try
            {
                socket.LinkObject.Connect(ip, Int32.Parse(port));
            }
            catch
            {
                if (socket != null)
                    socket = null;
                //if (this.timerInfo.Enabled==false)
                //    this.timerInfo.Start();
                //throw new Exception("未能连接上指挥中心，请等待！");
                return false;
            }
            socket.BeginAcceptData();
            this.timerInfo.Stop();
            return true;
        }
       
            
       

        void socket_OnStringDataAccept(string AccepterID, string AcceptData)
        {
            AddMsg(AcceptData);
        }

        void socket_OnSendTo(string SenderID, string EventMessage)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        void socket_OnSended(string SenderID, string EventMessage)
        {
            //string sendtime = DateTime.Now.ToLongTimeString().ToString();
           // AddMsg("Me: " + "客户端(" + sendtime + "):" + richTBOrder.Text + AsySocket.EndChar);
        }

        private void AddMsg(string msg)
        {
            if (richTBInfoDetail.InvokeRequired)
            {
                CallBackRef c = new CallBackRef(AddMsgCallBack);
                this.Invoke(c, new object[] { msg });
            }
            else
            {
                richTBInfoDetail.Text = msg + Environment.NewLine + richTBInfoDetail.Text;
            }
        }

        private void AddMsgCallBack(string msg)
        {
            //string a, b, c = "";
            //a = msg.Substring(0,msg.Length-1);
            //b = richTBInfoDetail.Text;
            //c = a + Environment.NewLine + b;
            //richTBInfoDetail.Text =c;
            richTBInfoDetail.Text = msg.Substring(0, msg.Length - 1) + Environment.NewLine + richTBInfoDetail.Text;
            //richTBInfoDetail.Text = "客户端(" + sendtime + "):" + richTBOrder.Text + Environment.NewLine + richTBInfoDetail.Text;
        }

        #endregion


        //接收消息
        public void getOrderMsg(WBMsgOrderMsg msg)
        {
            richTBInfoDetail.Text = msg.returnMsg+Environment.NewLine+richTBInfoDetail.Text;
        }

        //连接数据库
        public static SqlConnection SqlConnection()
        {
            try
            {
                SqlConnection sqlConn = null;
                sqlConn = new SqlConnection(SQLCONNSTR);
                sqlConn.Open();
                return sqlConn;
            }
            catch
            {
                throw new Exception("SQL Connection Error!");
            }
        }

        //现场力量
        private void btXcll_Click(object sender, EventArgs e)
        {
            if (panel9.Visible == true)
            {
                panel9.Visible = false;
                return;
            }
            tabYYFQ.Visible = false;
            panel9.Visible = true;
            this.panelLeft.Controls.Clear();
            this.panelRight.Controls.Clear();
            
            //进场车辆信息
            string sql1 = "select a.RFID,b.CarName as Name,b.CarUse as CarUse from InOutInfo a " +
                "inner join dbo.CarInfo b on a.RFID = b.RFID  ";
            SqlDataReader reader1 = null;
            SqlCommand cmd1 = new SqlCommand(sql1, dbConnect);
            reader1 = cmd1.ExecuteReader();
            int i = 0;

            while (reader1.Read())
            {
                string rfid = reader1["RFID"].ToString();
                string name = reader1["Name"].ToString();
                string caruse = reader1["CarUse"].ToString();

                Button b = new Button();
                if (caruse == "消防1")
                    b.Image = DrawinglimageList.Images[3];
                else
                    b.Image = DrawinglimageList.Images[4];

                b.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
                b.Location = new System.Drawing.Point(7, 3);
                b.Name = rfid;
                b.Size = new System.Drawing.Size(64, 66);
                b.TabIndex = i;
                b.Text = name;
                b.UseVisualStyleBackColor = true;
                b.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
                b.UseVisualStyleBackColor = true;
                b.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
                this.panelLeft.Controls.Add(b);
                b.Location = new Point(0, 5 + i * 70);
                Console.WriteLine(b.Location.Y.ToString());
                i++;
            }
            reader1.Close();

            //进场人员信息
            string sqluser = "select * from UserInfo where state='已出警'";
            SqlDataReader readerUser = null;
            SqlCommand cmdUser = new SqlCommand(sqluser, dbConnect);
            readerUser = cmdUser.ExecuteReader();
            int j = 0;
            while (readerUser.Read())
            {
                string rfid = readerUser["RFID"].ToString();
                string name = readerUser["UserName"].ToString();

                Button a = new Button();
                a.Image = DrawinglimageList.Images[2];
                a.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
                a.Location = new System.Drawing.Point(7, 3);
                a.Name = rfid;
                a.Size = new System.Drawing.Size(64, 66);
                a.TabIndex = j;
                a.Text = name;
                a.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
                a.UseVisualStyleBackColor = true;
                a.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
                this.panelRight.Controls.Add(a);
                a.Location = new Point(0, 5 + j * 70);
                Console.WriteLine(a.Location.Y.ToString());
                j++;
            }
            readerUser.Close();
        }

        //车辆信息
        private void btClxx_Click(object sender, EventArgs e)
        {
            if (panelLV.Visible == true)
            {
                //panelLV.Visible = false;
                hidePannel(panelLV);
                return;
            }
            panelLV.Visible = true;
            lvCarInfo.Clear();

            lvCarInfo.BeginUpdate();
            #region 增加Item的標題，共有三個列
            lvCarInfo.View = View.Details;
            lvCarInfo.Columns.Add("车辆名称", 120);
            lvCarInfo.Columns.Add("剩余泡沫", 80);
            lvCarInfo.Columns.Add("剩余油料", 80);
            #endregion

            string sql1 = "select a.RFID,b.CarName as Name,a.FoamSurplus,a.OilSurplus from InOutInfo a " +
                "inner join dbo.CarInfo b on a.RFID = b.RFID ";
            SqlDataReader reader1 = null;
            SqlCommand cmd1 = new SqlCommand(sql1, dbConnect);
            reader1 = cmd1.ExecuteReader();

            while (reader1.Read())
            {
                string rfid = reader1["RFID"].ToString();
                string name = reader1["Name"].ToString();
                string foam = reader1["FoamSurplus"].ToString();
                string oil = reader1["OilSurplus"].ToString();

                lvCarInfo.Items.Add(rfid, name, 0);
                lvCarInfo.Items[rfid].SubItems.Add(foam);
                lvCarInfo.Items[rfid].SubItems.Add(oil);
            }
            reader1.Close();
            lvCarInfo.EndUpdate();
        }
        //隐藏车辆信息
        private void btnCL_Click(object sender, EventArgs e)
        {
            hidePannel(panelLV);
        }

        //及时信息
        private void btQctj_Click(object sender, EventArgs e)
        {
            if (panelInfo.Visible == true)
            {
                panelInfo.Visible = false;
                return;
            }
            else
            {
                panelInfo.Visible = true;
            }
        }
       

        //隐藏Pannel
        private void hidePannel(Panel panel)
        {
            int width = panel.Width;
            int height = panel.Height;
            while (panel.Width > 2 && panel.Height > 2)
            {
                panel.Width = panel.Width - 2;
                panel.Height = panel.Height - 2;
            }
            panel.Visible = false;
            panel.Height = height;
            panel.Width = width;
        }

        #region 文字消息和指令

        //发送消息
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        //获取滚动条位置
        [DllImport("user32")]
        public static extern int GetScrollPos(IntPtr hwnd, int nBar);

        //设置滚动条位置
        [DllImport("user32.dll")]
        static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
        public const int EM_LINESCROLL = 0xb6;
       
        ////及时消息滚动
        //private void timerInfo_Tick(object sender, EventArgs e)
        //{
        //    return;
        //    int i = GetScrollPos(this.richTBInfo.Handle, 1);
        //    //向下滚动一行
        //    SendMessage(this.richTBInfo.Handle, EM_LINESCROLL, 0, 1);//0，1代表垂直滚动条向下滚动
        //    //判断是否有位置变化，如果没有则说明到了底部，返回开始处
        //    if (i == GetScrollPos(this.richTBInfo.Handle, 1))
        //    {
        //        //回到顶部，这里用SetScrollPos似乎有问题，滚动条和文字不是同步更新
        //        this.richTBInfo.SelectionStart = 0;
        //        this.richTBInfo.SelectionLength = 1;
        //        this.richTBInfo.ScrollToCaret();
        //        this.richTBInfo.SelectionLength = 0;
        //    }
        //    Console.WriteLine(i);


        //    int j = GetScrollPos(this.richTBInfoDetail.Handle, 1);
        //    //向下滚动一行
        //    SendMessage(this.richTBInfoDetail.Handle, EM_LINESCROLL, 0, 1);//0，1代表垂直滚动条向下滚动
        //    //判断是否有位置变化，如果没有则说明到了底部，返回开始处
        //    if (j == GetScrollPos(this.richTBInfoDetail.Handle, 1))
        //    {
        //        //回到顶部，这里用SetScrollPos似乎有问题，滚动条和文字不是同步更新
        //        this.richTBInfoDetail.SelectionStart = 0;
        //        this.richTBInfoDetail.SelectionLength = 1;
        //        this.richTBInfoDetail.ScrollToCaret();
        //        this.richTBInfoDetail.SelectionLength = 0;
        //    }
        //    Console.WriteLine(j);
        //}
       
        private void richTBInfo_MouseEnter_1(object sender, EventArgs e)
        {
            //this.timerInfo.Stop();
        }

        private void richTBInfo_MouseLeave_1(object sender, EventArgs e)
        {
            //this.timerInfo.Start();
        }

        private void richTBInfo_MouseEnter(object sender, EventArgs e)
        {
            //this.timerInfo.Stop();
        }

        private void richTBInfo_MouseLeave(object sender, EventArgs e)
        {
            //this.timerInfo.Start();
        }

        private void richTBInfo_Click(object sender, EventArgs e)
        {
            if (panelInfo.Visible == true)
            {
                panelInfo.Visible = false;
                return;
            }
            else
            {
                panelInfo.Visible = true;
            }
        }

        private void cbbOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            richTBOrder.Text = cbbOrder.Text;
        }

        private void btnClearOrder_Click(object sender, EventArgs e)
        {
            richTBOrder.Text = "";
            cbbOrder.Text = "";
        }
        

        //客户端消息发送 
        private void btnOrder_Click(object sender, EventArgs e)
        {
            if (richTBOrder.Text == "")
                return;

            panelInfo.Visible = true;

            string sendtime = DateTime.Now.ToLongTimeString().ToString();
            ////客户端消息发送
            //if (socketnetWork != null)
            //{
            //    WBMsgOrderMsg OrderMsg = new WBMsgOrderMsg();
            //    OrderMsg.returnMsg = "客户端(" + sendtime + "):" + richTBOrder.Text;
            //    socketnetWork.SendWBMsgConnectedHdlr(OrderMsg);
            //    richTBInfoDetail.Text = OrderMsg.returnMsg + Environment.NewLine + richTBInfoDetail.Text;
            //}
            //richTBOrder.Text = "";

            sendMsg(clientname+"(" + sendtime + "):" + richTBOrder.Text);
            //客户端消息发送
            //if (socket != null)
            //{
            //    socket.ASend("客户端(" + sendtime + "):" + richTBOrder.Text + AsySocket.EndChar);
            //    richTBInfoDetail.Text = "客户端(" + sendtime + "):" + richTBOrder.Text + Environment.NewLine + richTBInfoDetail.Text;
            //}
            //else
            //{
            //    if (InfoConnectServer() == true)
            //    {
            //        socket.ASend("客户端(" + sendtime + "):" + richTBOrder.Text + AsySocket.EndChar);
            //        richTBInfoDetail.Text = "客户端(" + sendtime + "):" + richTBOrder.Text + Environment.NewLine + richTBInfoDetail.Text;
            //    }
            //    else
            //    {
            //        MessageBox.Show(this, "指挥中心未能连接上，请稍侯再试。。。");
            //    }

            //}
            richTBOrder.Text = "";
        }


        private void sendMsg(string msg)
        {
            //客户端消息发送
            if (socket != null)
            {
                socket.ASend(msg + AsySocket.EndChar);
                //richTBInfoDetail.Text = msg + Environment.NewLine + richTBInfoDetail.Text;  //由服务端给所有客户端发送消息
            }
            else
            {
                if (InfoConnectServer() == true)
                {
                    socket.ASend(msg + AsySocket.EndChar);
                    //richTBInfoDetail.Text = msg + Environment.NewLine + richTBInfoDetail.Text;//由服务端给所有客户端发送消息
                }
                else
                {
                    MessageBox.Show(this, "指挥中心未能连接上，请稍侯再试。。。");
                }

            }
        }

        private void btXdml_Click(object sender, EventArgs e)
        {
            if (panelOrder.Visible == true)
            {
                //panelLeft.Visible = true;
                //panelRight.Visible = true;
                panelOrder.Visible = false;
                return;
            }
            else
            {
                panelOrder.Visible = true;
                //panelLeft.Visible = false;
                //panelRight.Visible = false;
            }
        }


        #endregion
        private void Form1_Resize(object sender, EventArgs e)
        {
            panelInfo.Width = Drawing.Width;
            richTBInfoDetail.Width = panelInfo.Width;
        }

      

        #region 图标命令
        private void pbOrder1_Click(object sender, EventArgs e)
        {
            string sendtime = DateTime.Now.ToLongTimeString().ToString();
            ////客户端消息发送
            //if (socketnetWork != null)
            //{
            //    WBMsgOrderMsg OrderMsg = new WBMsgOrderMsg();
            //    OrderMsg.returnMsg = "客户端(" + sendtime + "):图标指令-不要带易燃物进场！";// +AsySocket.EndChar;
            //    socketnetWork.SendWBMsgConnectedHdlr(OrderMsg);
            //    richTBInfoDetail.Text = OrderMsg.returnMsg + Environment.NewLine + richTBInfoDetail.Text;
            //}

            //客户端消息发送
            sendMsg(clientname+"(" + sendtime + "):图标指令-不要带易燃物进场！" );
            //if (socket != null)
            //{
            //    socket.ASend("客户端(" + sendtime + "):图标指令-不要带易燃物进场！"  + AsySocket.EndChar);
            //    richTBInfoDetail.Text = "客户端(" + sendtime + "):图标指令-不要带易燃物进场！" + Environment.NewLine + richTBInfoDetail.Text;
            //}
        }
       

        private void pbOrder2_Click(object sender, EventArgs e)
        {
            string sendtime = DateTime.Now.ToLongTimeString().ToString();
            //客户端消息发送
            //if (socketnetWork != null)
            //{
            //    WBMsgOrderMsg OrderMsg = new WBMsgOrderMsg();
            //    OrderMsg.returnMsg = "客户端(" + sendtime + "):图标指令-禁止用水灭火！";// +AsySocket.EndChar;
            //    socketnetWork.SendWBMsgConnectedHdlr(OrderMsg);
            //    richTBInfoDetail.Text = OrderMsg.returnMsg + Environment.NewLine + richTBInfoDetail.Text;
            //}

            //客户端消息发送
            sendMsg(clientname+"(" + sendtime + "):图标指令-禁止用水灭火！");
            //if (socket != null)
            //{
            //    socket.ASend("客户端(" + sendtime + "):图标指令-禁止用水灭火！" + AsySocket.EndChar);
            //    richTBInfoDetail.Text = "客户端(" + sendtime + "):图标指令-禁止用水灭火！" + Environment.NewLine + richTBInfoDetail.Text;
            //}

        }

        private void pbOrder3_Click(object sender, EventArgs e)
        {
            string sendtime = DateTime.Now.ToLongTimeString().ToString();
            //客户端消息发送
            sendMsg(clientname+"(" + sendtime + "):图标指令-禁止行人靠近！");
            //if (socketnetWork != null)
            //{
            //    WBMsgOrderMsg OrderMsg = new WBMsgOrderMsg();
            //    OrderMsg.returnMsg = "客户端(" + sendtime + "):图标指令-禁止行人靠近！";// +AsySocket.EndChar;
            //    socketnetWork.SendWBMsgConnectedHdlr(OrderMsg);
            //    richTBInfoDetail.Text = OrderMsg.returnMsg + Environment.NewLine + richTBInfoDetail.Text;
            //}
            //if (socket != null)
            //{
            //    socket.ASend("客户端(" + sendtime + "):图标指令-禁止行人靠近！" + AsySocket.EndChar);
            //    richTBInfoDetail.Text = "客户端(" + sendtime + "):图标指令-禁止行人靠近！" + Environment.NewLine + richTBInfoDetail.Text;
            //}
        }

        private void btnPicOrder_Click(object sender, EventArgs e)
        {
            
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            //this.WindowState = FormWindowState.Maximized;
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.BackColor = System.Drawing.Color.Black;
            //this.ClientSize = new System.Drawing.Size(1920, 1080);
            this.ControlBox = false;
            //this.Controls.AddRange(new System.Windows.Forms.Control[] { this.picture1, this.word });
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.KeyPreview = true;
            this.MaximizeBox = false;
            this.Name = "screen";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            //this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        }


        private void btnHideOrder_Click(object sender, EventArgs e)
        {
            if (panelOrder.Visible == true)
            {
                panelOrder.Visible = false;
                panel9.Visible = true;
                return;
            }
            else
            {
                panelOrder.Visible = true;
                panel9.Visible = false;
            }
        }

       

        private void btnInfoDetail_Click(object sender, EventArgs e)
        {
            if (panelInfo.Visible == true)
            {
                panelInfo.Visible = false;
                return;
            }
            else
                panelInfo.Visible = true;
        }

       

        private void pbSysTitle_Click(object sender, EventArgs e)
        {
                
        }
        private void btnPaint_Click(object sender, EventArgs e)
        {

            if (panelPaint.Visible == true)
            {
                btnPaint.Text = "显示画板";
                panelPaint.Visible = false;
                return;
            }
            else
            {
                panelPaint.Visible = true;
                btnPaint.Text = "隐藏画板";
            }
        }
        private void btJcxx_Click(object sender, EventArgs e)
        {
            if (panelPicOrder.Visible == true)
            {
                panelPicOrder.Visible = false;
                hidePannel(panelPicOrder);
                return;
            }
            panelPicOrder.Visible = true;
        }

        #endregion



        #region 冯曦
        /// <summary>
        /// 根据字符串得到配置节的字符串
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetConfigurationValue(string key)
        {
            return System.Configuration.ConfigurationManager.AppSettings[key];
        }
        /// <summary>
        /// 用来控制右边控制层显示的枚举
        /// </summary>
        public enum PannelControl
        {
            /// <summary>
            /// 现场力量
            /// </summary>
            XCLL,
            /// <summary>
            /// 下达命令
            /// </summary>
            XDML,
            /// <summary>
            /// 语音发起
            /// </summary>
            YYFQ,
            /// <summary>
            /// 侦查情况
            /// </summary>
            ZCQK
        }

        /// <summary>
        /// 控制右边的图层显示
        /// </summary>
        /// <param name="pan"></param>
        public void ControlPanel(PannelControl pan)
        {
            switch (pan)
            {
                case PannelControl.XCLL: //现场力量
                    panelXC.Visible = true;
                    //panelOrder.Visible = false;
                    tabYYFQ.Visible = false;
                    panel9.Visible = false;
                    break;
                case PannelControl.XDML: //下达命令
                    panelOrder.Visible = true;
                    //panelXC.Visible = false;
                    tabYYFQ.Visible = false;
                    panel9.Visible = false;
                    break;
                case PannelControl.YYFQ: //语音发起
                    tabYYFQ.Visible = true;
                    //panelXC.Visible = false;
                    panelOrder.Visible = false;
                    panel9.Visible = false;
                    break;
                case PannelControl.ZCQK: //侦查情况
                    panel9.Visible = true;
                    tabYYFQ.Visible = false;
                    //panelXC.Visible = false;
                    panelOrder.Visible = false;
                    break;
            }
        }

        private void btYyfq_Click(object sender, EventArgs e)
        {
            if (tabYYFQ.Visible == true)
            {
                tabYYFQ.Visible = false;
                return;
            }
            tabYYFQ.Visible = true;
            panel9.Visible = false;
            panelOrder.Visible = false;
            ControlPanel(PannelControl.YYFQ);

            if (IsInitBroadcasting)
            {
                this.tabYYFQ.SelectedTab = tabGB;
            }
            else
            {
                InitTabGB();
            }
        }

        /// <summary>
        /// InitAudio
        /// </summary>
        private void InitAudio()
        {
            try
            {
                CreateHandle();
                //InitComboboxes();
                LoadConfig();
                if (aduio_netWork == null)
                {
                    aduio_netWork = new NetworkManager(this, Audio_serverIP, Audio_serverPort, SOKET_TYPE.enServerMode);
                }
                aduio_netWork.StartListening();
                InitJitterBufferClientRecording();
                InitJitterBufferClientPlaying();
                InitJitterBufferServerRecording();
                InitTimerShowProgressBarPlayingClient();
                InitProtocolClient();        
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }


        /// <summary>
        /// 配置音频聊天的基本参数
        /// </summary>
        private void LoadConfig()
        {
            List<String> playbackNames = WinSound.WinSound.GetPlaybackNames();
            List<String> recordingNames = WinSound.WinSound.GetRecordingNames();

            //Output
            foreach (String name in playbackNames.Where(x => x != null))
            {
                m_Config.SoundOutputDeviceNameClient = name;
                m_Config.SoundOutputDeviceNameServer = name;

            }
            //Input
            foreach (String name in recordingNames.Where(x => x != null))
            {
                m_Config.SoundInputDeviceNameServer = name;
                m_Config.SoundInputDeviceNameClient = name;
            }

            m_Config.IpAddressClient = GetConfigurationValue("Client_AudioIP");
            m_Config.IPAddressServer = GetConfigurationValue("Server_AudioIP");
            m_Config.PortClient = Convert.ToInt32(GetConfigurationValue("Client_AudioPort"));
            m_Config.PortServer = Convert.ToInt32(GetConfigurationValue("Server_AudioPort"));
            m_Config.SamplesPerSecondClient = Convert.ToInt32(GetConfigurationValue("Client_SamplesPer"));
            m_Config.JitterBufferCountServer = Convert.ToUInt32(GetConfigurationValue("ServerJitter"));
            m_Config.JitterBufferCountClient = Convert.ToUInt32(GetConfigurationValue("ClientJitter"));
            m_Config.SamplesPerSecondServer = Convert.ToInt32(GetConfigurationValue("Server_SamplesPer"));
            m_Config.BitsPerSampleServer = 16;
            m_Config.BitsPerSampleClient = 16;
            m_Config.ChannelsServer = 2;
            m_Config.ChannelsClient = 2;
            m_Config.UseJitterBufferClientRecording = true;
            m_Config.UseJitterBufferServerRecording = true;
        }

        /// <summary>
        /// 语音监听服务的IP地址
        /// </summary>
        private static string Audio_serverIP = System.Configuration.ConfigurationManager.AppSettings["Audio_serverIP"];
        /// <summary>
        /// 语音监听服务的端口号
        /// </summary>
        private static string Audio_serverPort = System.Configuration.ConfigurationManager.AppSettings["Audio_serverPort"];
        /// <summary>
        /// 关于语音的服务SCOKET
        /// </summary>
        public NetworkManager aduio_netWork;
        /// <summary>
        /// 关于语音的客户SCOKET
        /// </summary>
        public NetworkManager aduio_client_netWork;
        
        public void ClientStart()
        {
            try
            {
                //Daten holen
                //FormToClientConfig();
                LoadConfig();

                if (IsClientConnected)
                {
                    DisconnectClient();
                    StopRecordingFromSounddevice_Client();
                }
                else
                {
                    ConnectClient();
                    StartRecordingFromSounddevice_Client();
                }
                //Kurz warten
                System.Threading.Thread.Sleep(100);

            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        private void tabYYFQ_Selected(object sender, TabControlEventArgs e)
        {
            if (e.TabPage == tabGB)
            {
                if (!IsInitBroadcasting)
                {
                    tabGB.Controls.Clear();
                    InitTabGB();
                }
            }
            if (e.TabPage == tabSL)
            {
                if (!IsInitCall)
                {
                    tabSL.Controls.Clear();
                    InitTabSL();
                }
            }    
        }

        /// <summary>
        /// 初始化所有语音广播的对象
        /// </summary>
        private void InitTabGB()
        {
            //进场人员信息
            //string Self_IP = GetConfigurationValue("Client_AudioIP");
            //string sqluser = "select * from UserInfo where state='已出警' and ipaddr='" + Self_IP + "'";
            ////SqlDataReader readerUser = null;
            //SqlCommand cmdUser = new SqlCommand(sqluser, dbConnect);
            //SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
            ////SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
            //DataTable dt = new DataTable();
            //adapter.Fill(dt);
            //readerUser = cmdUser.ExecuteReader();
            int j = 0;
            TableLayoutPanel tmpPanel = new TableLayoutPanel();
            tmpPanel.ColumnCount = 2;
            tmpPanel.Name = "tabUsers";
            //tmpPanel.RowCount = dt.Rows.Count + 1;
            tmpPanel.RowCount = 2;
            tmpPanel.Refresh();//刷新panel
            Size ka = new Size();//new 一个size
            ka.Width = 200;
            //ka.Height = 75 * (dt.Rows.Count + 1);
            ka.Height = 75 * 2;
            tmpPanel.Size = ka;

            
            tmpPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 70));
            tmpPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 40));

            for (int h = 0; h < tmpPanel.RowStyles.Count; h++)
            {
                tmpPanel.RowStyles[h].SizeType = SizeType.Absolute;
                tmpPanel.RowStyles[h].Height = 30;

            }
            Button tmpA = new Button();            
            tmpA.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            tmpA.Location = new System.Drawing.Point(7, 3);
            tmpA.Name = "zhzff";
            tmpA.Size = new System.Drawing.Size(70, 40);
            tmpA.TabIndex = j;
            tmpA.Text = "指挥中心";
            tmpA.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            tmpA.UseVisualStyleBackColor = true;
            //tmpA.Click += new System.EventHandler(this.BtnBroadcasting_Click);
            tmpPanel.Controls.Add(tmpA);


            Button tmpC = new Button();
            tmpC.Location = new System.Drawing.Point(7, 3);
            tmpC.FlatStyle = FlatStyle.Flat;
            tmpC.FlatAppearance.BorderSize = 0;
            tmpC.Name = "btnBroadcastingControl";
            tmpC.Size = new System.Drawing.Size(40, 40);
            tmpC.Image = Properties.Resources.Speak_On;
            tmpC.ImageAlign = System.Drawing.ContentAlignment.TopLeft;
            tmpC.TabIndex = j;
            tmpC.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            tmpC.UseVisualStyleBackColor = true;
            //tmpC.Click += new System.EventHandler(this.BtnBroadcasting_Click);
            tmpPanel.Controls.Add(tmpC);
            //for (int iCount = 0; iCount < dt.Rows.Count; iCount++)
            //{
            //    string rfid = dt.Rows[iCount]["RFID"].ToString();
            //    string name = dt.Rows[iCount]["UserName"].ToString();
            //    CheckBox ckTmp = new CheckBox();
            //    ckTmp.Text = "";
            //    ckTmp.Name = "Item|" + dt.Rows[iCount]["ipaddr"].ToString();
            //    ckTmp.Checked = false;
            //    //ckTmp.Click += new System.EventHandler(this.CheckBoxItemSelect_Click);
            //    tmpPanel.Controls.Add(ckTmp);

            //    Button a = new Button();
            //    a.Image = DrawinglimageList.Images[2];
            //    a.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //    a.Location = new System.Drawing.Point(7, 3);
            //    a.Name = rfid;
            //    a.Size = new System.Drawing.Size(120, 70);
            //    a.TabIndex = j;
            //    a.Text = name;
            //    a.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //    a.UseVisualStyleBackColor = true;
            //    a.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
            //    tmpPanel.Controls.Add(a);
            //    Button c = new Button();
            //    c.Location = new System.Drawing.Point(7, 3);
            //    c.Name = rfid;
            //    c.Size = new System.Drawing.Size(48, 48);
            //    c.Image = Properties.Resources.Listen_On;
            //    c.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //    c.TabIndex = j;
            //    c.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //    c.UseVisualStyleBackColor = true;
            //    c.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
            //    tmpPanel.Controls.Add(c);
            //    //this.panelRight.Controls.Add(a);

            //    //c.Location = new Point(0, 5 + j * 70);
            //    //Console.WriteLine(a.Location.Y.ToString());
            //    j++;
            //}
            this.tabGB.Controls.Add(tmpPanel);
            IsInitBroadcasting = true;
        }

        private void InitTabSL()
        {
            //进场人员信息
            //string sqluser = "select * from UserInfo where state='已出警'";
            ////SqlDataReader readerUser = null;
            //SqlCommand cmdUser = new SqlCommand(sqluser, dbConnect);
            //SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
            ////SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
            //DataTable dt = new DataTable();
            //adapter.Fill(dt);
            //readerUser = cmdUser.ExecuteReader();
            int j = 0;
            TableLayoutPanel tmpPanel = new TableLayoutPanel();
            tmpPanel.ColumnCount = 3;
            tmpPanel.Name = "tabSLUsers";
            //tmpPanel.RowCount = dt.Rows.Count + 1;
            tmpPanel.RowCount = 2;
            tmpPanel.Refresh();//刷新panel
            Size ka = new Size();//new 一个size
            ka.Width = 250;
            //ka.Height = 75 * (dt.Rows.Count + 1);
            ka.Height = 75 * 2;

            tmpPanel.Size = ka;

            for (int h = 0; h < tmpPanel.RowStyles.Count; h++)
            {
                tmpPanel.RowStyles[h].SizeType = SizeType.Absolute;
                tmpPanel.RowStyles[h].Height = 20;

            }


            Button tmpA = new Button();
            tmpA.Location = new System.Drawing.Point(7, 3);
            tmpA.Name = "Caller|" + Audio_serverIP;
            tmpA.Size = new System.Drawing.Size(73, 44);
            tmpA.TabIndex = j;
            tmpA.Text = "指挥中心";
            tmpA.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            tmpA.UseVisualStyleBackColor = true;            
            tmpPanel.Controls.Add(tmpA,0,0);
            tmpPanel.SetRowSpan(tmpA, 2);
            
            Button tmpC = new Button();
            tmpC.Location = new System.Drawing.Point(7, 3);
            tmpC.Name = "CallIn|" + Audio_serverIP;
            tmpC.Text = "呼叫";
            tmpC.Size = new System.Drawing.Size(57, 20);
            tmpC.TabIndex = j;
            tmpC.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //c.Click += new EventHandler(this.BtnPerToPer_Click);
            //tmpPanel.Controls.Add(tmpC);
            tmpPanel.Controls.Add(tmpC, 1, 0);
            Button tmpD = new Button();
            tmpD.Location = new System.Drawing.Point(7, 3);
            tmpD.Name = "CallOut|" + Audio_serverIP;
            tmpD.Text = "取消";
            tmpD.Enabled = false;
            tmpD.Size = new System.Drawing.Size(57, 20);
            tmpD.TabIndex = j;
            tmpD.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //dd.Click += new EventHandler(this.BtnPerToPer_Click);
            //tmpPanel.Controls.Add(tmpD);
            tmpPanel.Controls.Add(tmpD, 1,1);

            //Button tmpA = new Button();
            //tmpA.Image = DrawinglimageList.Images[2];
            //tmpA.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //tmpA.Location = new System.Drawing.Point(7, 3);
            //tmpA.Name = "zhzff";
            //tmpA.Size = new System.Drawing.Size(120, 70);
            //tmpA.TabIndex = j;
            //tmpA.Text = "指挥中心";
            //tmpA.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //tmpA.UseVisualStyleBackColor = true;
            //tmpA.Click += new System.EventHandler(this.BtnBroadcasting_Click);
            //tmpPanel.Controls.Add(tmpA);


            //Button tmpC = new Button();
            //tmpC.Location = new System.Drawing.Point(7, 3);
            //tmpC.Name = "btnBroadcastingControl";
            //tmpC.Text = "呼叫";
            //tmpC.Size = new System.Drawing.Size(55, 23);
            ////tmpC.Image = DrawinglimageList.Images[6];            
            //tmpC.TabIndex = j;
            //tmpC.TextAlign = System.Drawing.ContentAlignment.BottomCenter;            
            //tmpC.Click += new System.EventHandler(this.BtnBroadcasting_Click);
            //tmpPanel.Controls.Add(tmpC);
            //Button tmpD = new Button();
            //tmpD.Location = new System.Drawing.Point(7, 3);
            //tmpD.Name = "btnBroadcastingControl";
            //tmpD.Text = "取消";
            //tmpD.Size = new System.Drawing.Size(55, 23);
            ////tmpD.Image = DrawinglimageList.Images[6];            
            //tmpD.TabIndex = j;
            //tmpD.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //tmpD.Click += new System.EventHandler(this.BtnBroadcasting_Click);
            //tmpPanel.Controls.Add(tmpD);
            //for (int iCount = 0; iCount < dt.Rows.Count; iCount++)
            //{
            //    string rfid = dt.Rows[iCount]["RFID"].ToString();
            //    string name = dt.Rows[iCount]["UserName"].ToString();



            //    Button a = new Button();
            //    a.Image = DrawinglimageList.Images[2];
            //    a.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //    a.Location = new System.Drawing.Point(7, 3);
            //    a.Name = "Caller|" + dt.Rows[iCount]["ipaddr"].ToString();
            //    a.Size = new System.Drawing.Size(120, 70);
            //    a.TabIndex = j;
            //    a.Text = name;
            //    a.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //    a.UseVisualStyleBackColor = true;
            //    a.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
            //    tmpPanel.Controls.Add(a);
            //    Button c = new Button();
            //    c.Location = new System.Drawing.Point(7, 3);
            //    c.Name = "CallIn|" + dt.Rows[iCount]["ipaddr"].ToString();
            //    c.Text = "呼叫";
            //    c.Size = new System.Drawing.Size(55, 23);
            //    c.TabIndex = j;
            //    c.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //    c.Click += new EventHandler(this.BtnPerToPer_Click);
            //    tmpPanel.Controls.Add(c);
            //    Button dd = new Button();
            //    dd.Location = new System.Drawing.Point(7, 3);
            //    dd.Name = "CallOut|" + dt.Rows[iCount]["ipaddr"].ToString();
            //    dd.Text = "取消";
            //    dd.Enabled = false;
            //    dd.Size = new System.Drawing.Size(55, 23);
            //    dd.TabIndex = j;
            //    dd.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            //    dd.Click += new EventHandler(this.BtnPerToPer_Click);
            //    tmpPanel.Controls.Add(dd);
            //    //this.panelRight.Controls.Add(a);

            //    //c.Location = new Point(0, 5 + j * 70);
            //    //Console.WriteLine(a.Location.Y.ToString());
            //    j++;
            //}
            this.tabSL.Controls.Add(tmpPanel);
            IsInitCall = true;
        }

        //private TableLayoutPanel ReturnTabGB()
        //{
        //    //进场人员信息
        //    string Self_IP = GetConfigurationValue("Client_AudioIP");
        //    string sqluser = "select * from UserInfo where state='已出警' and ipaddr='" + Self_IP + "'";
        //    //SqlDataReader readerUser = null;
        //    SqlCommand cmdUser = new SqlCommand(sqluser, dbConnect);
        //    SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
        //    //SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
        //    DataTable dt = new DataTable();
        //    adapter.Fill(dt);
        //    int j = 0;
        //    TableLayoutPanel tmpPanel = new TableLayoutPanel();
        //    tmpPanel.ColumnCount = 2;
        //    tmpPanel.RowCount = dt.Rows.Count + 1;
        //    tmpPanel.Refresh();//刷新panel
        //    Size ka = new Size();//new 一个size
        //    ka.Width = 200;
        //    ka.Height = 75 * (dt.Rows.Count + 1);

        //    tmpPanel.Size = ka;

        //    for (int h = 0; h < tmpPanel.RowStyles.Count; h++)
        //    {
        //        tmpPanel.RowStyles[h].SizeType = SizeType.Absolute;
        //        tmpPanel.RowStyles[h].Height = 30;

        //    }
        //    Button tmpA = new Button();
        //    tmpA.Image = DrawinglimageList.Images[2];
        //    tmpA.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //    tmpA.Location = new System.Drawing.Point(7, 3);
        //    tmpA.Name = "zhzff";
        //    tmpA.Size = new System.Drawing.Size(82, 48);
        //    tmpA.TabIndex = j;
        //    tmpA.Text = "指挥中心";
        //    tmpA.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //    tmpA.UseVisualStyleBackColor = true;
        //    //tmpA.Click += new System.EventHandler(this.BtnBroadcasting_Click);
        //    tmpPanel.Controls.Add(tmpA);


        //    Button tmpC = new Button();
        //    tmpC.Location = new System.Drawing.Point(7, 3);
        //    tmpC.Name = "btnBroadcastingControl";
        //    tmpC.Size = new System.Drawing.Size(48, 48);
        //    tmpC.Image = DrawinglimageList.Images[6];
        //    tmpC.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //    tmpC.TabIndex = j;
        //    tmpC.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //    tmpC.UseVisualStyleBackColor = true;
        //    //tmpC.Click += new System.EventHandler(this.BtnBroadcasting_Click);
        //    tmpPanel.Controls.Add(tmpC);
        //    for (int iCount = 0; iCount < dt.Rows.Count; iCount++)
        //    {
        //        string rfid = dt.Rows[iCount]["RFID"].ToString();
        //        string name = dt.Rows[iCount]["UserName"].ToString();



        //        Button a = new Button();
        //        a.Image = DrawinglimageList.Images[2];
        //        a.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //        a.Location = new System.Drawing.Point(7, 3);
        //        a.Name = rfid;
        //        a.Size = new System.Drawing.Size(82, 48);
        //        a.TabIndex = j;
        //        a.Text = name;
        //        a.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //        a.UseVisualStyleBackColor = true;
        //        a.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
        //        tmpPanel.Controls.Add(a);
        //        Button c = new Button();
        //        c.Location = new System.Drawing.Point(7, 3);
        //        c.Name = rfid;
        //        c.Size = new System.Drawing.Size(48, 48);
        //        c.Image = DrawinglimageList.Images[5];
        //        c.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //        c.TabIndex = j;
        //        c.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //        c.UseVisualStyleBackColor = true;
        //        c.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
        //        tmpPanel.Controls.Add(c);
        //        //this.panelRight.Controls.Add(a);

        //        //c.Location = new Point(0, 5 + j * 70);
        //        //Console.WriteLine(a.Location.Y.ToString());
        //        j++;
        //    }
        //    return tmpPanel;
        //}

        //private TableLayoutPanel ReturnTabSL()
        //{
        //    //进场人员信息
        //    string sqluser = "select * from UserInfo where state='已出警'";
        //    //SqlDataReader readerUser = null;
        //    SqlCommand cmdUser = new SqlCommand(sqluser, dbConnect);
        //    SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
        //    //SqlDataAdapter adapter = new SqlDataAdapter(cmdUser);
        //    DataTable dt = new DataTable();
        //    adapter.Fill(dt);
        //    //readerUser = cmdUser.ExecuteReader();
        //    int j = 0;
        //    TableLayoutPanel tmpPanel = new TableLayoutPanel();
        //    tmpPanel.ColumnCount = 2;
        //    tmpPanel.RowCount = dt.Rows.Count + 1;
        //    tmpPanel.Refresh();//刷新panel
        //    Size ka = new Size();//new 一个size
        //    ka.Width = 200;
        //    ka.Height = 75 * (dt.Rows.Count + 1);

        //    tmpPanel.Size = ka;

        //    for (int h = 0; h < tmpPanel.RowStyles.Count; h++)
        //    {
        //        tmpPanel.RowStyles[h].SizeType = SizeType.Absolute;
        //        tmpPanel.RowStyles[h].Height = 30;

        //    }
        //    Button tmpA = new Button();
        //    tmpA.Image = DrawinglimageList.Images[2];
        //    tmpA.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //    tmpA.Location = new System.Drawing.Point(7, 3);
        //    tmpA.Name = "zhzff";
        //    tmpA.Size = new System.Drawing.Size(120, 70);
        //    tmpA.TabIndex = j;
        //    tmpA.Text = "指挥中心";
        //    tmpA.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //    tmpA.UseVisualStyleBackColor = true;
        //    //tmpA.Click += new System.EventHandler(this.BtnBroadcasting_Click);
        //    tmpPanel.Controls.Add(tmpA);


        //    Button tmpC = new Button();
        //    tmpC.Location = new System.Drawing.Point(7, 3);
        //    tmpC.Name = "btnBroadcastingControl";
        //    tmpC.Size = new System.Drawing.Size(48, 48);
        //    tmpC.Image = DrawinglimageList.Images[6];
        //    tmpC.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //    tmpC.TabIndex = j;
        //    tmpC.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //    tmpC.UseVisualStyleBackColor = true;
        //    //tmpC.Click += new System.EventHandler(this.BtnBroadcasting_Click);
        //    tmpPanel.Controls.Add(tmpC);
        //    for (int iCount = 0; iCount < dt.Rows.Count; iCount++)
        //    {
        //        string rfid = dt.Rows[iCount]["RFID"].ToString();
        //        string name = dt.Rows[iCount]["UserName"].ToString();



        //        Button a = new Button();
        //        a.Image = DrawinglimageList.Images[2];
        //        a.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //        a.Location = new System.Drawing.Point(7, 3);
        //        a.Name = rfid;
        //        a.Size = new System.Drawing.Size(120, 70);
        //        a.TabIndex = j;
        //        a.Text = name;
        //        a.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //        a.UseVisualStyleBackColor = true;
        //        a.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
        //        tmpPanel.Controls.Add(a);
        //        Button c = new Button();
        //        c.Location = new System.Drawing.Point(7, 3);
        //        c.Name = rfid;
        //        c.Size = new System.Drawing.Size(48, 48);
        //        c.Image = DrawinglimageList.Images[5];
        //        c.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //        c.TabIndex = j;
        //        c.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
        //        c.UseVisualStyleBackColor = true;
        //        c.MouseDown += new System.Windows.Forms.MouseEventHandler(this.carDrafting_MouseDown);
        //        tmpPanel.Controls.Add(c);
        //        //this.panelRight.Controls.Add(a);

        //        //c.Location = new Point(0, 5 + j * 70);
        //        //Console.WriteLine(a.Location.Y.ToString());
        //        j++;
        //    }
        //    return tmpPanel;
        //}



        //Attribute
        private NF.TCPClient m_Client;
        private NF.TCPServer m_Server;
        private Configuration m_Config = new Configuration();
        private String m_ConfigFileName = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "config.xml");
        private int m_SoundBufferCount = 8;
        private WinSound.Protocol m_PrototolClient = new WinSound.Protocol(WinSound.ProtocolTypes.LH, Encoding.Default);
        private Dictionary<NF.ServerThread, ServerThreadData> m_DictionaryServerDatas = new Dictionary<NF.ServerThread, ServerThreadData>();
        private WinSound.Recorder m_Recorder_Client;
        private WinSound.Recorder m_Recorder_Server;
        private WinSound.Player m_PlayerClient;
        private uint m_RecorderFactor = 4;
        private WinSound.JitterBuffer m_JitterBufferClientRecording;
        private WinSound.JitterBuffer m_JitterBufferClientPlaying;
        private WinSound.JitterBuffer m_JitterBufferServerRecording;
        WinSound.WaveFileHeader m_FileHeader = new WinSound.WaveFileHeader();
        private bool m_IsFormMain = true;
        private long m_SequenceNumber = 4596;
        private long m_TimeStamp = 0;
        private int m_Version = 2;
        private bool m_Padding = false;
        private bool m_Extension = false;
        private int m_CSRCCount = 0;
        private bool m_Marker = false;
        private int m_PayloadType = 0;
        private uint m_SourceId = 0;
        private System.Windows.Forms.Timer m_TimerProgressBarFile = new System.Windows.Forms.Timer();
        private System.Windows.Forms.Timer m_TimerProgressBarPlayingClient = new System.Windows.Forms.Timer();
        private WinSound.EventTimer m_TimerStream = new WinSound.EventTimer();
        private Byte[] m_FilePayloadBuffer;
        private int m_RTPPartsLength = 0;
        private uint m_Milliseconds = 20;
        System.Windows.Forms.Timer m_TimerDrawProgressBar;
        private Object LockerDictionary = new Object();
        //是否初始化广播
        private bool IsInitBroadcasting = false;
        //是否初始化点对点语音
        private bool IsInitCall = false;

        /// <summary>
        /// Init
        /// </summary>
        private void Init()
        {
            try
            {
                CreateHandle();
                InitComboboxes();
                LoadConfig();
                InitJitterBufferClientRecording();
                InitJitterBufferClientPlaying();
                InitJitterBufferServerRecording();
                InitTimerShowProgressBarPlayingClient();
                InitProtocolClient();
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// InitProtocolClient
        /// </summary>
        private void InitProtocolClient()
        {
            if (m_PrototolClient != null)
            {
                m_PrototolClient.DataComplete += new WinSound.Protocol.DelegateDataComplete(OnProtocolClient_DataComplete);
            }
        }
        /// <summary>
        /// FillRTPBufferWithPayloadData
        /// </summary>
        /// <param name="header"></param>
        private void FillRTPBufferWithPayloadData(WinSound.WaveFileHeader header)
        {
            m_RTPPartsLength = WinSound.Utils.GetBytesPerInterval(header.SamplesPerSecond, header.BitsPerSample, header.Channels);
            m_FilePayloadBuffer = header.Payload;
        }
        /// <summary>
        /// InitTimerShowProgressBarPlayingClient
        /// </summary>
        private void InitTimerShowProgressBarPlayingClient()
        {
            m_TimerProgressBarPlayingClient = new System.Windows.Forms.Timer();
            m_TimerProgressBarPlayingClient.Interval = 60;
            m_TimerProgressBarPlayingClient.Tick += new EventHandler(OnTimerProgressPlayingClient);
        }
        /// <summary>
        /// OnTimerProgressPlayingClient
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void OnTimerProgressPlayingClient(Object obj, EventArgs e)
        {
            try
            {
                if (m_PlayerClient != null)
                {
                    ProgressBarPlayingClient.Value = Math.Min(m_JitterBufferClientPlaying.Length, ProgressBarPlayingClient.Maximum);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("FormMain.cs | OnTimerProgressPlayingClient() | {0}", ex.Message));
                m_TimerProgressBarPlayingClient.Stop();
            }
        }
        /// <summary>
        /// InitJitterBufferClientRecording
        /// </summary>
        private void InitJitterBufferClientRecording()
        {
            //Wenn vorhanden
            if (m_JitterBufferClientRecording != null)
            {
                m_JitterBufferClientRecording.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailableRecording);
            }

            //Neu erstellen
            m_JitterBufferClientRecording = new WinSound.JitterBuffer(null, 20, 20);
            m_JitterBufferClientRecording.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailableRecording);
        }
        /// <summary>
        /// InitJitterBufferClientPlaying
        /// </summary>
        private void InitJitterBufferClientPlaying()
        {
            //Wenn vorhanden
            if (m_JitterBufferClientPlaying != null)
            {
                m_JitterBufferClientPlaying.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailablePlaying);
            }

            //Neu erstellen
            m_JitterBufferClientPlaying = new WinSound.JitterBuffer(null, m_Config.JitterBufferCountClient, 20);
            m_JitterBufferClientPlaying.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailablePlaying);
        }
        /// <summary>
        /// InitJitterBuffer
        /// </summary>
        private void InitJitterBufferServerRecording()
        {
            //Wenn vorhanden
            if (m_JitterBufferServerRecording != null)
            {
                m_JitterBufferServerRecording.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferServerDataAvailable);
            }

            //Neu erstellen
            m_JitterBufferServerRecording = new WinSound.JitterBuffer(null, 20, 20);
            m_JitterBufferServerRecording.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferServerDataAvailable);
        }
        /// <summary>
        /// UseJitterBuffer
        /// </summary>
        private bool UseJitterBufferServer
        {
            get
            {
                return m_Config.JitterBufferCountServer >= 2;
            }
        }
        /// <summary>
        /// UseJitterBuffer
        /// </summary>
        private bool UseJitterBufferClientRecording
        {
            get
            {
                return m_Config.UseJitterBufferClientRecording;
            }
        }
        /// <summary>
        /// UseJitterBufferServerRecording
        /// </summary>
        private bool UseJitterBufferServerRecording
        {
            get
            {
                return m_Config.UseJitterBufferServerRecording;
            }
        }
        /// <summary>
        /// StartRecordingFromSounddevice_Client
        /// </summary>
        private void StartRecordingFromSounddevice_Client()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Client == false)
                {
                    //Buffer Grösse berechnen
                    int bufferSize = 0;
                    if (UseJitterBufferClientRecording)
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient) * (int)m_RecorderFactor;
                    }
                    else
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                    }

                    //Wenn Buffer korrekt
                    if (bufferSize > 0)
                    {
                        //Recorder erstellen
                        m_Recorder_Client = new WinSound.Recorder();

                        //Events hinzufügen
                        m_Recorder_Client.DataRecorded += new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Client);
                        m_Recorder_Client.RecordingStopped += new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Client);

                        //Recorder starten
                        if (m_Recorder_Client.Start(m_Config.SoundInputDeviceNameClient, m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient, m_SoundBufferCount, bufferSize))
                        {
                            //Anzeigen
                            ShowStreamingFromSounddeviceStarted_Client();

                            //Wenn JitterBuffer
                            if (UseJitterBufferClientRecording)
                            {
                                m_JitterBufferClientRecording.Start();
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// StartRecordingFromSounddevice_Server
        /// </summary>
        private void StartRecordingFromSounddevice_Server()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Server == false)
                {
                    //Buffer Grösse berechnen
                    int bufferSize = 0;
                    if (UseJitterBufferServerRecording)
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer) * (int)m_RecorderFactor;
                    }
                    else
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);
                    }

                    //Wenn Buffer korrekt
                    if (bufferSize > 0)
                    {
                        //Recorder erstellen
                        m_Recorder_Server = new WinSound.Recorder();

                        //Events hinzufügen
                        m_Recorder_Server.DataRecorded += new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Server);
                        m_Recorder_Server.RecordingStopped += new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Server);

                        //Recorder starten
                        if (m_Recorder_Server.Start(m_Config.SoundInputDeviceNameServer, m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer, m_SoundBufferCount, bufferSize))
                        {
                            //Anzeigen
                            ShowStreamingFromSounddeviceStarted_Server();

                            //JitterBuffer starten
                            m_JitterBufferServerRecording.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// StopRecordingFromSounddevice_Client
        /// </summary>
        private void StopRecordingFromSounddevice_Client()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Client)
                {
                    //Stoppen
                    m_Recorder_Client.Stop();

                    //Events entfernen
                    m_Recorder_Client.DataRecorded -= new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Client);
                    m_Recorder_Client.RecordingStopped -= new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Client);
                    m_Recorder_Client = null;

                    //Wenn JitterBuffer
                    if (UseJitterBufferClientRecording)
                    {
                        m_JitterBufferClientRecording.Stop();
                    }

                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Client();
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// StopRecordingFromSounddevice_Server
        /// </summary>
        private void StopRecordingFromSounddevice_Server()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Server)
                {
                    //Stoppen
                    m_Recorder_Server.Stop();

                    //Events entfernen
                    m_Recorder_Server.DataRecorded -= new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Server);
                    m_Recorder_Server.RecordingStopped -= new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Server);
                    m_Recorder_Server = null;

                    //JitterBuffer beenden
                    m_JitterBufferServerRecording.Stop();

                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Server();
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// OnRecordingStopped
        /// </summary>
        private void OnRecordingStopped_Client()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Client();

                }));
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// OnRecordingStopped_Server
        /// </summary>
        private void OnRecordingStopped_Server()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Server();

                }));
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// OnDataReceivedFromSoundcard_Client
        /// </summary>
        /// <param name="linearData"></param>
        private void OnDataReceivedFromSoundcard_Client(Byte[] data)
        {
            try
            {
                lock (this)
                {
                    if (IsClientConnected)
                    {
                        //Wenn gewünscht
                        if (m_Config.ClientNoSpeakAll == false)
                        {
                            //Sounddaten in kleinere Einzelteile zerlegen
                            int bytesPerInterval = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                            int count = data.Length / bytesPerInterval;
                            int currentPos = 0;
                            for (int i = 0; i < count; i++)
                            {
                                //Teilstück in RTP Packet umwandeln
                                Byte[] partBytes = new Byte[bytesPerInterval];
                                Array.Copy(data, currentPos, partBytes, 0, bytesPerInterval);
                                currentPos += bytesPerInterval;
                                WinSound.RTPPacket rtp = ToRTPPacket(partBytes, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);

                                //Wenn JitterBuffer
                                if (UseJitterBufferClientRecording)
                                {
                                    //In Buffer legen
                                    m_JitterBufferClientRecording.AddData(rtp);
                                }
                                else
                                {
                                    //Alles in RTP Packet umwandeln
                                    Byte[] rtpBytes = ToRTPData(data, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                                    //Absenden
                                    m_Client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnDataReceivedFromSoundcard_Server
        /// </summary>
        /// <param name="data"></param>
        private void OnDataReceivedFromSoundcard_Server(Byte[] data)
        {
            try
            {
                lock (this)
                {
                    if (IsServerRunning)
                    {
                        //Wenn Form noch aktiv
                        if (m_IsFormMain)
                        {
                            //Wenn gewünscht
                            if (m_Config.ServerNoSpeakAll == false)
                            {
                                //Sounddaten in kleinere Einzelteile zerlegen
                                int bytesPerInterval = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);
                                int count = data.Length / bytesPerInterval;
                                int currentPos = 0;
                                for (int i = 0; i < count; i++)
                                {
                                    //Teilstück in RTP Packet umwandeln
                                    Byte[] partBytes = new Byte[bytesPerInterval];
                                    Array.Copy(data, currentPos, partBytes, 0, bytesPerInterval);
                                    currentPos += bytesPerInterval;
                                    WinSound.RTPPacket rtp = ToRTPPacket(partBytes, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);

                                    //Wenn JitterBuffer
                                    if (UseJitterBufferServerRecording)
                                    {
                                        //In Buffer legen
                                        m_JitterBufferServerRecording.AddData(rtp);
                                    }
                                    else
                                    {
                                        //RTP Packet in Bytes umwandeln
                                        Byte[] rtpBytes = rtp.ToBytes();

                                        //Für alle Clients
                                        foreach (NF.ServerThread client in m_Server.Clients)
                                        {
                                            //Wenn nicht Mute
                                            if (client.IsMute == false)
                                            {
                                                //Absenden
                                                client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnJitterBufferClientDataAvailable
        /// </summary>
        /// <param name="rtp"></param>
        private void OnJitterBufferClientDataAvailableRecording(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (IsClientConnected)
                {
                    if (m_IsFormMain)
                    {
                        //RTP Packet in Bytes umwandeln
                        Byte[] rtpBytes = rtp.ToBytes();
                        //Absenden
                        m_Client.Send(m_PrototolClient.ToBytes(rtpBytes));
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// OnJitterBufferClientDataAvailablePlaying
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rtp"></param>
        private void OnJitterBufferClientDataAvailablePlaying(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (m_PlayerClient != null)
                {
                    if (m_PlayerClient.Opened)
                    {
                        if (m_IsFormMain)
                        {
                            //Wenn nicht stumm
                            if (m_Config.MuteClientPlaying == false)
                            {
                                //Nach Linear umwandeln
                                Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                                //Abspielen
                                m_PlayerClient.PlayData(linearBytes, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// OnJitterBufferServerDataAvailable
        /// </summary>
        /// <param name="rtp"></param>
        private void OnJitterBufferServerDataAvailable(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (IsServerRunning)
                {
                    if (m_IsFormMain)
                    {
                        //RTP Packet in Bytes umwandeln
                        Byte[] rtpBytes = rtp.ToBytes();

                        //Für alle Clients
                        List<NF.ServerThread> list = new List<NF.ServerThread>(m_Server.Clients);
                        foreach (NF.ServerThread client in list)
                        {
                            //Wenn nicht Mute
                            if (client.IsMute == false)
                            {
                                try
                                {
                                    //Absenden
                                    client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                }
                                catch (Exception)
                                {
                                    //Eintrag löschen
                                    RemoveControlInAllFlowLayoutPanelsByServerThread(client);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// ToRTPData
        /// </summary>
        /// <param name="linearData"></param>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        /// <returns></returns>
        private Byte[] ToRTPData(Byte[] data, int bitsPerSample, int channels)
        {
            //Neues RTP Packet erstellen
            WinSound.RTPPacket rtp = ToRTPPacket(data, bitsPerSample, channels);
            //RTPHeader in Bytes erstellen
            Byte[] rtpBytes = rtp.ToBytes();
            //Fertig
            return rtpBytes;
        }
        /// <summary>
        /// ToRTPPacket
        /// </summary>
        /// <param name="linearData"></param>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        /// <returns></returns>
        private WinSound.RTPPacket ToRTPPacket(Byte[] linearData, int bitsPerSample, int channels)
        {
            //Daten Nach MuLaw umwandeln
            Byte[] mulaws = WinSound.Utils.LinearToMulaw(linearData, bitsPerSample, channels);

            //Neues RTP Packet erstellen
            WinSound.RTPPacket rtp = new WinSound.RTPPacket();

            //Werte übernehmen
            rtp.Data = mulaws;
            rtp.CSRCCount = m_CSRCCount;
            rtp.Extension = m_Extension;
            rtp.HeaderLength = WinSound.RTPPacket.MinHeaderLength;
            rtp.Marker = m_Marker;
            rtp.Padding = m_Padding;
            rtp.PayloadType = m_PayloadType;
            rtp.Version = m_Version;
            rtp.SourceId = m_SourceId;

            //RTP Header aktualisieren
            try
            {
                rtp.SequenceNumber = Convert.ToUInt16(m_SequenceNumber);
                m_SequenceNumber++;
            }
            catch (Exception)
            {
                m_SequenceNumber = 0;
            }
            try
            {
                rtp.Timestamp = Convert.ToUInt32(m_TimeStamp);
                m_TimeStamp += mulaws.Length;
            }
            catch (Exception)
            {
                m_TimeStamp = 0;
            }

            //Fertig
            return rtp;
        }
        /// <summary>
        /// IsRecorderStarted
        /// </summary>
        private bool IsRecorderFromSounddeviceStarted_Client
        {
            get
            {
                if (m_Recorder_Client != null)
                {
                    return m_Recorder_Client.Started;
                }
                return false;
            }
        }
        /// <summary>
        /// IsRecorderFromSounddeviceStarted_Server
        /// </summary>
        private bool IsRecorderFromSounddeviceStarted_Server
        {
            get
            {
                if (m_Recorder_Server != null)
                {
                    return m_Recorder_Server.Started;
                }
                return false;
            }
        }
        /// <summary>
        /// InitComboboxes
        /// </summary>
        private void InitComboboxes()
        {
            InitComboboxesClient();
            InitComboboxesServer();

            ComboboxSamplesPerSecond.SelectedIndex = 1;
        }
        /// <summary>
        /// InitComboboxesClient
        /// </summary>
        private void InitComboboxesClient()
        {
            ComboboxOutputSoundDeviceNameClient.Items.Clear();
            ComboboxInputSoundDeviceNameClient.Items.Clear();
            List<String> playbackNames = WinSound.WinSound.GetPlaybackNames();
            List<String> recordingNames = WinSound.WinSound.GetRecordingNames();

            //Output
            ComboboxOutputSoundDeviceNameClient.Items.Add("None");
            foreach (String name in playbackNames.Where(x => x != null))
            {
                ComboboxOutputSoundDeviceNameClient.Items.Add(name);
            }
            //Input
            foreach (String name in recordingNames.Where(x => x != null))
            {
                ComboboxInputSoundDeviceNameClient.Items.Add(name);
            }

            //Output
            if (ComboboxOutputSoundDeviceNameClient.Items.Count > 0)
            {
                ComboboxOutputSoundDeviceNameClient.SelectedIndex = 0;
            }
            //Input
            if (ComboboxInputSoundDeviceNameClient.Items.Count > 0)
            {
                ComboboxInputSoundDeviceNameClient.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// InitComboboxesServer
        /// </summary>
        private void InitComboboxesServer()
        {
            ComboboxOutputSoundDeviceNameServer.Items.Clear();
            ComboboxInputSoundDeviceNameServer.Items.Clear();
            List<String> playbackNames = WinSound.WinSound.GetPlaybackNames();
            List<String> recordingNames = WinSound.WinSound.GetRecordingNames();

            //Output
            foreach (String name in playbackNames.Where(x => x != null))
            {
                ComboboxOutputSoundDeviceNameServer.Items.Add(name);
            }
            //Input
            foreach (String name in recordingNames.Where(x => x != null))
            {
                ComboboxInputSoundDeviceNameServer.Items.Add(name);
            }

            //Output
            if (ComboboxOutputSoundDeviceNameServer.Items.Count > 0)
            {
                ComboboxOutputSoundDeviceNameServer.SelectedIndex = 0;
            }
            //Input
            if (ComboboxInputSoundDeviceNameServer.Items.Count > 0)
            {
                ComboboxInputSoundDeviceNameServer.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// ConnectClient
        /// </summary>
        private void ConnectClient()
        {
            try
            {
                if (IsClientConnected == false)
                {
                    //Wenn Eingabe vorhanden
                    if (m_Config.IpAddressClient.Length > 0 && m_Config.PortClient > 0)
                    {
                        m_Client = new NF.TCPClient(m_Config.IpAddressClient, m_Config.PortClient);
                        m_Client.ClientConnected += new NF.TCPClient.DelegateConnection(OnClientConnected);
                        m_Client.ClientDisconnected += new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                        m_Client.ExceptionAppeared += new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                        m_Client.DataReceived += new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                        m_Client.Connect();
                    }
                }
            }
            catch (Exception ex)
            {
                m_Client = null;
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// DisconnectClient
        /// </summary>
        private void DisconnectClient()
        {
            try
            {
                //Aufnahme beenden
                StopRecordingFromSounddevice_Client();

                if (m_Client != null)
                {
                    //Client beenden
                    m_Client.Disconnect();
                    m_Client.ClientConnected -= new NF.TCPClient.DelegateConnection(OnClientConnected);
                    m_Client.ClientDisconnected -= new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                    m_Client.ExceptionAppeared -= new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                    m_Client.DataReceived -= new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                    m_Client = null;
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// StartServer
        /// </summary>
        private void StartServer()
        {
            try
            {
                if (IsServerRunning == false)
                {
                    if (m_Config.IPAddressServer.Length > 0 && m_Config.PortServer > 0)
                    {
                        m_Server = new NF.TCPServer();
                        m_Server.ClientConnected += new NF.TCPServer.DelegateClientConnected(OnServerClientConnected);
                        m_Server.ClientDisconnected += new NF.TCPServer.DelegateClientDisconnected(OnServerClientDisconnected);
                        m_Server.DataReceived += new NF.TCPServer.DelegateDataReceived(OnServerDataReceived);
                        m_Server.Start(m_Config.IPAddressServer, m_Config.PortServer);

                        //Je nach Server Status
                        if (m_Server.State == NF.TCPServer.ListenerState.Started)
                        {
                            ShowServerStarted();
                        }
                        else
                        {
                            ShowServerStopped();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// StopServer
        /// </summary>
        private void StopServer()
        {
            try
            {
                if (IsServerRunning == true)
                {

                    //Player beenden
                    DeleteAllServerThreadDatas();

                    //Server beenden
                    m_Server.Stop();
                    m_Server.ClientConnected -= new NF.TCPServer.DelegateClientConnected(OnServerClientConnected);
                    m_Server.ClientDisconnected -= new NF.TCPServer.DelegateClientDisconnected(OnServerClientDisconnected);
                    m_Server.DataReceived -= new NF.TCPServer.DelegateDataReceived(OnServerDataReceived);
                }

                //Je nach Server Status
                if (m_Server != null)
                {
                    if (m_Server.State == NF.TCPServer.ListenerState.Started)
                    {
                        ShowServerStarted();
                    }
                    else
                    {
                        ShowServerStopped();
                    }
                }

                //Fertig
                m_Server = null;
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// OnClientConnected
        /// </summary>
        /// <param name="client"></param>
        /// <param name="info"></param>
        private void OnClientConnected(NF.TCPClient client, string info)
        {
            ShowMessage(LabelClient, String.Format("Client connected {0}", ""));
            ShowClientConnected();
            StartPlayingToSounddevice_Client();
        }
        /// <summary>
        /// OnClientDisconnected
        /// </summary>
        /// <param name="client"></param>
        /// <param name="info"></param>
        private void OnClientDisconnected(NF.TCPClient client, string info)
        {
            //Abspielen beenden
            StopPlayingToSounddevice_Client();
            //Streamen von Sounddevice beenden
            StopRecordingFromSounddevice_Client();

            if (m_Client != null)
            {
                m_Client.ClientConnected -= new NF.TCPClient.DelegateConnection(OnClientConnected);
                m_Client.ClientDisconnected -= new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                m_Client.ExceptionAppeared -= new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                m_Client.DataReceived -= new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                ShowMessage(LabelClient, String.Format("Client disconnected {0}", ""));
            }

            ShowClientDisconnected();
        }
        /// <summary>
        /// OnClientExceptionAppeared
        /// </summary>
        /// <param name="client"></param>
        /// <param name="ex"></param>
        private void OnClientExceptionAppeared(NF.TCPClient client, Exception ex)
        {
            DisconnectClient();
            ShowError(LabelClient, ex.Message);
        }
        /// <summary>
        /// OnClientDataReceived
        /// </summary>
        /// <param name="client"></param>
        /// <param name="bytes"></param>
        private void OnClientDataReceived(NF.TCPClient client, Byte[] bytes)
        {
            try
            {
                if (m_PrototolClient != null)
                {
                    m_PrototolClient.Receive_LH(client, bytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnProtocolClient_DataComplete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void OnProtocolClient_DataComplete(Object sender, Byte[] data)
        {
            try
            {
                //Wenn der Player gestartet wurde
                if (m_PlayerClient != null)
                {
                    if (m_PlayerClient.Opened)
                    {
                        //RTP Header auslesen
                        WinSound.RTPPacket rtp = new WinSound.RTPPacket(data);

                        //Wenn Header korrekt
                        if (rtp.Data != null)
                        {
                            //In JitterBuffer hinzufügen
                            if (m_JitterBufferClientPlaying != null)
                            {
                                m_JitterBufferClientPlaying.AddData(rtp);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnServerClientConnected
        /// </summary>
        /// <param name="st"></param>
        private void OnServerClientConnected(NF.ServerThread st)
        {
            try
            {
                //ServerThread Daten erstellen
                ServerThreadData data = new ServerThreadData();
                //Initialisieren
                data.Init(st, m_Config.SoundOutputDeviceNameServer, m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer, m_SoundBufferCount, m_Config.JitterBufferCountServer, m_Milliseconds);
                //Hinzufügen
                m_DictionaryServerDatas[st] = data;
                //Zu FlowLayoutPanels hinzufügen
                AddServerClientToFlowLayoutPanel_ServerClient(st);
                AddServerClientToFlowLayoutPanel_ServerProgressBars(data);
                AddServerClientToFlowLayoutPanel_ServerListenButtons(data);
                AddServerClientToFlowLayoutPanel_ServerSpeakButtons(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnServerClientDisconnected
        /// </summary>
        /// <param name="st"></param>
        /// <param name="info"></param>
        private void OnServerClientDisconnected(NF.ServerThread st, string info)
        {
            try
            {
                //Wenn vorhanden
                if (m_DictionaryServerDatas.ContainsKey(st))
                {
                    //Alle Daten freigeben
                    ServerThreadData data = m_DictionaryServerDatas[st];
                    data.Dispose();
                    lock (LockerDictionary)
                    {
                        //Entfernen
                        m_DictionaryServerDatas.Remove(st);
                    }
                    //Aus FlowLayoutPanels entfernen
                    RemoveServerClientToFlowLayoutPanel_ServerClient(st);
                    RemoveServerClientToFlowLayoutPanel_ServerProgressBar(data);
                    RemoveServerClientToFlowLayoutPanel_ButtonListen(data);
                    RemoveServerClientToFlowLayoutPanel_ButtonSpeak(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// StartTimerDrawProgressBar
        /// </summary>
        private void StartTimerDrawProgressBar()
        {
            if (m_TimerDrawProgressBar == null)
            {
                m_TimerDrawProgressBar = new System.Windows.Forms.Timer();
                m_TimerDrawProgressBar.Tick += new EventHandler(OnTimerDrawServerClientsProgressBars);
                m_TimerDrawProgressBar.Interval = 100;
                m_TimerDrawProgressBar.Start();
            }
        }
        /// <summary>
        ///StopTimerDrawCurve 
        /// </summary>
        private void StopTimerDrawProgressBar()
        {
            try
            {
                if (m_TimerDrawProgressBar != null)
                {
                    m_TimerDrawProgressBar.Stop();
                    m_TimerDrawProgressBar = null;

                    //Für jede ProgressBar
                    foreach (ProgressBar prog in FlowLayoutPanelServerProgressBars.Controls)
                    {
                        if (prog.Tag != null)
                        {
                            //Daten ermitteln
                            ServerThreadData stData = (ServerThreadData)prog.Tag;

                            //Wenn ein JitterBuffer vorhanden
                            if (stData.JitterBuffer != null)
                            {
                                prog.Value = 0;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnTimerDrawServerClientsProgressBars
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void OnTimerDrawServerClientsProgressBars(Object obj, EventArgs e)
        {
            try
            {
                //Für jede ProgressBar
                foreach (ProgressBar prog in FlowLayoutPanelServerProgressBars.Controls)
                {
                    if (prog.Tag != null)
                    {
                        //Daten ermitteln
                        ServerThreadData stData = (ServerThreadData)prog.Tag;

                        //Wenn ein JitterBuffer vorhanden
                        if (stData.JitterBuffer != null)
                        {
                            prog.Value = stData.JitterBuffer.Length;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// RemoveControlByTag
        /// </summary>
        /// <param name="controls"></param>
        /// <param name="tag"></param>
        private void RemoveControlByTag(Control.ControlCollection controls, object tag)
        {
            this.Invoke(new MethodInvoker(delegate()
            {
                //Control anhand Tag ermitteln
                Control existing = null;
                foreach (Control ctrl in controls)
                {
                    if (ctrl.Tag == tag)
                    {
                        existing = ctrl;
                        break;
                    }
                }

                //Wenn vorhanden
                if (existing != null)
                {
                    controls.Remove(existing);
                }
            }));
        }
        /// <summary>
        /// RemoveControlInAllFlowLayoutPanelsByServerThread
        /// </summary>
        /// <param name="st"></param>
        private void RemoveControlInAllFlowLayoutPanelsByServerThread(NF.ServerThread st)
        {
            this.Invoke(new MethodInvoker(delegate()
            {
                //Label
                Control ctrlLabel = null;
                foreach (Control ctrl in FlowLayoutPanelServerClients.Controls)
                {
                    NF.ServerThread thread = (NF.ServerThread)ctrl.Tag;
                    if (thread == st)
                    {
                        ctrlLabel = ctrl;
                        break;
                    }
                }
                if (ctrlLabel != null)
                {
                    FlowLayoutPanelServerClients.Controls.Remove(ctrlLabel);
                }

                //ProgressBar
                Control ctrlProgress = null;
                foreach (Control ctrl in FlowLayoutPanelServerProgressBars.Controls)
                {
                    ServerThreadData data = (ServerThreadData)ctrl.Tag;
                    if (data.ServerThread == st)
                    {
                        ctrlProgress = ctrl;
                        break;
                    }
                }
                if (ctrlProgress != null)
                {
                    FlowLayoutPanelServerProgressBars.Controls.Remove(ctrlProgress);
                }

                //ListenButton
                Control ctrlListen = null;
                foreach (Control ctrl in FlowLayoutPanelServerListen.Controls)
                {
                    ServerThreadData data = (ServerThreadData)ctrl.Tag;
                    if (data.ServerThread == st)
                    {
                        ctrlListen = ctrl;
                        break;
                    }
                }
                if (ctrlListen != null)
                {
                    FlowLayoutPanelServerListen.Controls.Remove(ctrlListen);
                }

                //SpeakButton
                Control ctrlSpeak = null;
                foreach (Control ctrl in FlowLayoutPanelServerSpeak.Controls)
                {
                    ServerThreadData data = (ServerThreadData)ctrl.Tag;
                    if (data.ServerThread == st)
                    {
                        ctrlSpeak = ctrl;
                        break;
                    }
                }
                if (ctrlSpeak != null)
                {
                    FlowLayoutPanelServerSpeak.Controls.Remove(ctrlSpeak);
                }

            }));
        }
        /// <summary>
        /// RemoveServerClientToFlowLayoutPanel_ServerClient
        /// </summary>
        /// <param name="st"></param>
        private void RemoveServerClientToFlowLayoutPanel_ServerClient(NF.ServerThread st)
        {
            try
            {
                FlowLayoutPanelServerClients.Invoke(new MethodInvoker(delegate()
                {
                    //Label löschen
                    RemoveControlByTag(FlowLayoutPanelServerClients.Controls, st);

                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// RemoveServerClientToFlowLayoutPanel_ButtonListen
        /// </summary>
        /// <param name="st"></param>
        private void RemoveServerClientToFlowLayoutPanel_ButtonListen(ServerThreadData data)
        {
            try
            {
                FlowLayoutPanelServerListen.Invoke(new MethodInvoker(delegate()
                {
                    //Button löschen
                    RemoveControlByTag(FlowLayoutPanelServerListen.Controls, data);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// RemoveServerClientToFlowLayoutPanel_ButtonSpeak
        /// </summary>
        /// <param name="data"></param>
        private void RemoveServerClientToFlowLayoutPanel_ButtonSpeak(ServerThreadData data)
        {
            try
            {
                FlowLayoutPanelServerSpeak.Invoke(new MethodInvoker(delegate()
                {
                    //Button löschen
                    RemoveControlByTag(FlowLayoutPanelServerSpeak.Controls, data);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// AddServerClientToFlowLayoutPanel_ServerClient
        /// </summary>
        /// <param name="st"></param>
        private void AddServerClientToFlowLayoutPanel_ServerClient(NF.ServerThread st)
        {
            try
            {
                FlowLayoutPanelServerClients.Invoke(new MethodInvoker(delegate()
                {
                    //Label erstellen
                    Label lab = new Label();
                    lab.AutoSize = false;
                    lab.BackColor = Color.DimGray;
                    lab.ForeColor = Color.White;
                    lab.Font = new Font(lab.Font, FontStyle.Bold);
                    lab.Margin = new Padding(5, FlowLayoutPanelServerClients.Controls.Count > 0 ? 5 : 10, 0, 5);
                    lab.TextAlign = ContentAlignment.MiddleCenter;
                    lab.Width = FlowLayoutPanelServerClients.Width - 10;
                    lab.Text = st.Client.Client.RemoteEndPoint.ToString();
                    lab.Tag = st;

                    //Hinzufügen
                    FlowLayoutPanelServerClients.Controls.Add(lab);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// AddServerClientToFlowLayoutPanel_ServerProgressBars
        /// </summary>
        /// <param name="st"></param>
        private void AddServerClientToFlowLayoutPanel_ServerProgressBars(ServerThreadData stData)
        {
            try
            {
                FlowLayoutPanelServerProgressBars.Invoke(new MethodInvoker(delegate()
                {
                    //ProgressBar erstellen
                    ProgressBar prog = new ProgressBar();
                    prog.AutoSize = false;
                    prog.Margin = new Padding(5, FlowLayoutPanelServerProgressBars.Controls.Count > 0 ? 5 : 10, 0, 5);
                    prog.Width = FlowLayoutPanelServerProgressBars.Width - 20;
                    prog.BackColor = Color.White;
                    //prog.Maximum = (int)stData.JitterBuffer.Maximum;
                    prog.Tag = stData;

                    //Hinzufügen
                    FlowLayoutPanelServerProgressBars.Controls.Add(prog);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// AddServerClientToFlowLayoutPanel_ServerListenButtons
        /// </summary>
        /// <param name="stData"></param>
        private void AddServerClientToFlowLayoutPanel_ServerListenButtons(ServerThreadData stData)
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    //Button Listen erstellen
                    Button btnListen = new Button();
                    btnListen.Width = 26;
                    btnListen.Height = 27;
                    btnListen.Margin = new Padding(0, FlowLayoutPanelServerListen.Controls.Count > 0 ? 3 : 8, 0, 3);
                    btnListen.Tag = stData;
                    btnListen.BackColor = Color.LightGray;
                    btnListen.ImageAlign = ContentAlignment.MiddleCenter;
                    btnListen.Image = Properties.Resources.Listen_On_Small;
                    btnListen.Tag = stData;
                    btnListen.MouseClick += new MouseEventHandler(OnButtonServerThreadListenClick);

                    //Hinzufügen
                    FlowLayoutPanelServerListen.Controls.Add(btnListen);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// AddServerClientToFlowLayoutPanel_ServerSpeakButtons
        /// </summary>
        /// <param name="stData"></param>
        private void AddServerClientToFlowLayoutPanel_ServerSpeakButtons(ServerThreadData stData)
        {
            try
            {
                FlowLayoutPanelServerSpeak.Invoke(new MethodInvoker(delegate()
                {
                    //Button Listen erstellen
                    Button btnSpeak = new Button();
                    btnSpeak.Width = 26;
                    btnSpeak.Height = 27;
                    btnSpeak.Margin = new Padding(0, FlowLayoutPanelServerSpeak.Controls.Count > 0 ? 3 : 8, 0, 3);
                    btnSpeak.Tag = stData;
                    btnSpeak.ImageAlign = ContentAlignment.MiddleCenter;
                    btnSpeak.BackColor = Color.LightGray;
                    btnSpeak.Image = Properties.Resources.Speak_On_Small;
                    btnSpeak.Tag = stData;
                    btnSpeak.MouseClick += new MouseEventHandler(OnButtonServerThreadSpeakClick);

                    //Hinzufügen
                    FlowLayoutPanelServerSpeak.Controls.Add(btnSpeak);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnButtonServerThreadListenClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnButtonServerThreadListenClick(Object sender, MouseEventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                if (btn.Tag != null)
                {
                    ServerThreadData data = (ServerThreadData)btn.Tag;
                    //Mute toggeln
                    data.IsMute = !data.IsMute;

                    //Anzeigen
                    if (data.IsMute)
                    {
                        btn.Image = Properties.Resources.Listen_Off_Small;
                    }
                    else
                    {
                        btn.Image = Properties.Resources.Listen_On_Small;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// OnButtonServerThreadSpeakClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnButtonServerThreadSpeakClick(Object sender, MouseEventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                if (btn.Tag != null)
                {
                    ServerThreadData data = (ServerThreadData)btn.Tag;
                    //Mute toggeln
                    data.ServerThread.IsMute = !data.ServerThread.IsMute;

                    //Anzeigen
                    if (data.ServerThread.IsMute)
                    {
                        btn.Image = Properties.Resources.Speak_Off_Small;
                    }
                    else
                    {
                        btn.Image = Properties.Resources.Speak_On_Small;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// RemoveServerClientToFlowLayoutPanel_ServerProgressBar
        /// </summary>
        /// <param name="st"></param>
        private void RemoveServerClientToFlowLayoutPanel_ServerProgressBar(ServerThreadData data)
        {
            try
            {
                FlowLayoutPanelServerProgressBars.Invoke(new MethodInvoker(delegate()
                {
                    //ProgressBar löschen
                    RemoveControlByTag(FlowLayoutPanelServerProgressBars.Controls, data);
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// OnServerDataReceived
        /// </summary>
        /// <param name="st"></param>
        /// <param name="data"></param>
        private void OnServerDataReceived(NF.ServerThread st, Byte[] data)
        {
            //Wenn vorhanden
            if (m_DictionaryServerDatas.ContainsKey(st))
            {
                //Wenn Protocol
                ServerThreadData stData = m_DictionaryServerDatas[st];
                if (stData.Protocol != null)
                {
                    stData.Protocol.Receive_LH(st, data);
                }
            }
        }
        /// <summary>
        /// DeleteAllServerThreadDatas
        /// </summary>
        private void DeleteAllServerThreadDatas()
        {
            lock (LockerDictionary)
            {
                try
                {
                    foreach (ServerThreadData info in m_DictionaryServerDatas.Values)
                    {
                        info.Dispose();
                    }
                    m_DictionaryServerDatas.Clear();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        /// <summary>
        ///IsServerRunning 
        /// </summary>
        private bool IsServerRunning
        {
            get
            {
                if (m_Server != null)
                {
                    return m_Server.State == NF.TCPServer.ListenerState.Started;
                }
                return false;
            }
        }
        /// <summary>
        /// IsClientConnected
        /// </summary>
        private bool IsClientConnected
        {
            get
            {
                if (m_Client != null)
                {
                    return m_Client.Connected;
                }
                return false;
            }
        }
        /// <summary>
        /// ShowClientConnected
        /// </summary>
        private void ShowClientConnected()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    ButtonClient.BackColor = Color.DarkGreen;
                    TextBoxClientAddress.Enabled = false;
                    TextBoxClientPort.Enabled = false;
                    ComboboxSamplesPerSecond.Enabled = false;
                    NumericUpDownJitterBufferClient.Enabled = false;
                    ComboboxOutputSoundDeviceNameClient.Enabled = false;
                    ComboboxInputSoundDeviceNameClient.Enabled = false;
                    ProgressBarPlayingClient.Visible = true;
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// ShowClientDisconnected
        /// </summary>
        private void ShowClientDisconnected()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    ButtonClient.BackColor = Color.Gray;
                    TextBoxClientAddress.Enabled = true;
                    TextBoxClientPort.Enabled = true;
                    ComboboxSamplesPerSecond.Enabled = true;
                    NumericUpDownJitterBufferClient.Enabled = true;
                    ComboboxOutputSoundDeviceNameClient.Enabled = true;
                    ComboboxInputSoundDeviceNameClient.Enabled = true;
                    ProgressBarPlayingClient.Visible = false;
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// ShowServerStarted 
        /// </summary>
        private void ShowServerStarted()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    Button control = (Button)this.tabGB.Controls.Find("btnBroadcastingControl", true)[0];
                    control.Image = Properties.Resources.red;
                    ButtonServer.BackColor = Color.DarkGreen;
                    NumericUpDownJitterBufferServer.Enabled = false;
                    ComboboxOutputSoundDeviceNameServer.Enabled = false;
                    ComboboxInputSoundDeviceNameServer.Enabled = false;
                    TextBoxServerAddress.Enabled = false;
                    TextBoxServerPort.Enabled = false;
                    ComboboxSamplesPerSecondServer.Enabled = false;
                    StartTimerDrawProgressBar();
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// ShowServerStopped
        /// </summary>
        private void ShowServerStopped()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    Button control = (Button)this.tabGB.Controls.Find("btnBroadcastingControl", true)[0];
                    control.Image = Properties.Resources.green;
                    ButtonServer.BackColor = Color.Gray;
                    StopTimerDrawProgressBar();
                    FlowLayoutPanelServerClients.Controls.Clear();
                    FlowLayoutPanelServerProgressBars.Controls.Clear();
                    FlowLayoutPanelServerListen.Controls.Clear();
                    FlowLayoutPanelServerSpeak.Controls.Clear();
                    NumericUpDownJitterBufferServer.Enabled = true;
                    ComboboxOutputSoundDeviceNameServer.Enabled = true;
                    ComboboxInputSoundDeviceNameServer.Enabled = true;
                    TextBoxServerAddress.Enabled = true;
                    TextBoxServerPort.Enabled = true;
                    ComboboxSamplesPerSecondServer.Enabled = true;
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromSounddeviceStarted 
        /// </summary>
        private void ShowStreamingFromSounddeviceStarted_Client()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStarted_Client();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromSounddeviceStopped_Client 
        /// </summary>
        private void ShowStreamingFromSounddeviceStopped_Client()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStopped_Client();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromSounddeviceStarted_Server
        /// </summary>
        private void ShowStreamingFromSounddeviceStarted_Server()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStarted_Server();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromSounddeviceStopped_Server
        /// </summary>
        private void ShowStreamingFromSounddeviceStopped_Server()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStopped_Server();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromFileStarted 
        /// </summary>
        private void ShowStreamingFromFileStarted()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromFileStarted();
                    }));
                }
                else
                {
                    ComboboxInputSoundDeviceNameClient.Enabled = false;
                    ProgressBarPlayingClient.Visible = true;
                    ComboboxSamplesPerSecond.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowStreamingFromFileStopped 
        /// </summary>
        private void ShowStreamingFromFileStopped()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromFileStopped();
                    }));
                }
                else
                {
                    ComboboxInputSoundDeviceNameClient.Enabled = true;
                    ProgressBarPlayingClient.Visible = false;
                    ComboboxSamplesPerSecond.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ShowError
        /// </summary>
        /// <param name="lb"></param>
        /// <param name="text"></param>
        private void ShowError(Label lb, string text)
        {
            try
            {
                lb.Invoke(new MethodInvoker(delegate()
                {
                    lb.Text = text;
                    lb.ForeColor = Color.Red;

                    //Je nach Quelle
                    if (lb == LabelClient)
                    {
                        ButtonClient.BackColor = Color.Red;
                    }
                    else if (lb == LabelServer)
                    {
                        ButtonServer.BackColor = Color.Red;
                    }
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// ShowInfo
        /// </summary>
        /// <param name="lb"></param>
        /// <param name="text"></param>
        private void ShowMessage(Label lb, string text)
        {
            try
            {
                lb.Invoke(new MethodInvoker(delegate()
                {
                    lb.Text = text;
                    lb.ForeColor = Color.Black;
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// FormToConfig
        /// </summary>
        /// <returns></returns>
        private bool FormToConfig()
        {
            try
            {
                m_Config.IpAddressClient = TextBoxClientAddress.Text;
                m_Config.IPAddressServer = TextBoxServerAddress.Text;
                m_Config.PortClient = Convert.ToInt32(TextBoxClientPort.Text);
                m_Config.PortServer = Convert.ToInt32(TextBoxServerPort.Text);
                m_Config.SoundInputDeviceNameClient = ComboboxInputSoundDeviceNameClient.SelectedIndex >= 0 ? ComboboxInputSoundDeviceNameClient.SelectedItem.ToString() : "";
                m_Config.SoundOutputDeviceNameClient = ComboboxOutputSoundDeviceNameClient.SelectedIndex >= 0 ? ComboboxOutputSoundDeviceNameClient.SelectedItem.ToString() : "";
                m_Config.SoundInputDeviceNameServer = ComboboxInputSoundDeviceNameServer.SelectedIndex >= 0 ? ComboboxInputSoundDeviceNameServer.SelectedItem.ToString() : "";
                m_Config.SoundOutputDeviceNameServer = ComboboxOutputSoundDeviceNameServer.SelectedIndex >= 0 ? ComboboxOutputSoundDeviceNameServer.SelectedItem.ToString() : "";
                m_Config.SamplesPerSecondClient = ComboboxSamplesPerSecond.SelectedIndex >= 0 ? Convert.ToInt32(ComboboxSamplesPerSecond.SelectedItem.ToString()) : 8000;
                m_Config.JitterBufferCountServer = (uint)NumericUpDownJitterBufferServer.Value;
                m_Config.JitterBufferCountClient = (uint)NumericUpDownJitterBufferClient.Value;
                m_Config.SamplesPerSecondServer = ComboboxSamplesPerSecondServer.SelectedIndex >= 0 ? Convert.ToInt32(ComboboxSamplesPerSecondServer.SelectedItem.ToString()) : 8000;
                m_Config.BitsPerSampleServer = 16;
                m_Config.BitsPerSampleClient = 16;
                m_Config.ChannelsServer = 2;
                m_Config.ChannelsClient = 2;
                m_Config.UseJitterBufferClientRecording = true;
                m_Config.UseJitterBufferServerRecording = true;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Fehler bei der Eingabe", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        /// <summary>
        /// ConfigToForm
        /// </summary>
        /// <returns></returns>
        private bool ConfigToForm()
        {
            try
            {
                TextBoxClientAddress.Text = m_Config.IpAddressClient.ToString();
                TextBoxServerAddress.Text = m_Config.IPAddressServer.ToString();
                TextBoxClientPort.Text = m_Config.PortClient.ToString();
                TextBoxServerPort.Text = m_Config.PortServer.ToString();
                ComboboxInputSoundDeviceNameClient.SelectedIndex = ComboboxInputSoundDeviceNameClient.FindString(m_Config.SoundInputDeviceNameClient);
                ComboboxOutputSoundDeviceNameClient.SelectedIndex = ComboboxOutputSoundDeviceNameClient.FindString(m_Config.SoundOutputDeviceNameClient);
                ComboboxInputSoundDeviceNameServer.SelectedIndex = ComboboxInputSoundDeviceNameServer.FindString(m_Config.SoundInputDeviceNameServer);
                ComboboxOutputSoundDeviceNameServer.SelectedIndex = ComboboxOutputSoundDeviceNameServer.FindString(m_Config.SoundOutputDeviceNameServer);
                ComboboxSamplesPerSecond.SelectedIndex = ComboboxSamplesPerSecond.FindString(m_Config.SamplesPerSecondClient.ToString());
                NumericUpDownJitterBufferServer.Value = m_Config.JitterBufferCountServer;
                NumericUpDownJitterBufferClient.Value = m_Config.JitterBufferCountClient;
                ComboboxSamplesPerSecondServer.SelectedIndex = ComboboxSamplesPerSecondServer.FindString(m_Config.SamplesPerSecondServer.ToString());

                //Sonstiges
                ShowButtonServerSpeak();
                ShowButtonClientListen();
                ShowButtonServerListen();
                ShowButtonClientSpeak();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
        //----------------------------------------------------------------
        //Daten schreiben
        //----------------------------------------------------------------
        private void SaveConfig()
        {
            //try
            //{
            //    FormToConfig();
            //    XmlSerializer ser = new XmlSerializer(typeof(Configuration));
            //    FileStream stream = new FileStream(m_ConfigFileName, FileMode.Create);
            //    ser.Serialize(stream, m_Config);
            //    stream.Close();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }
        //----------------------------------------------------------------
        //Daten lesen
        //---------------------------------------------------------------- 


        /// <summary>
        /// ButtonClient_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonClient_Click(object sender, EventArgs e)
        {
            try
            {
                //Daten holen
                FormToConfig();

                if (IsClientConnected)
                {
                    DisconnectClient();
                    StopRecordingFromSounddevice_Client();
                }
                else
                {
                    ConnectClient();
                    StartRecordingFromSounddevice_Client();
                }

                //Kurz warten
                System.Threading.Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }
        /// <summary>
        /// ButtonServer_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonServer_Click(object sender, EventArgs e)
        {
            try
            {
                //Daten holen
                FormToConfig();

                if (IsServerRunning)
                {
                    StopServer();
                    StopRecordingFromSounddevice_Server();
                }
                else
                {
                    StartServer();
                    StartRecordingFromSounddevice_Server();
                }
            }
            catch (Exception ex)
            {
                ShowError(LabelServer, ex.Message);
            }
        }
        /// <summary>
        /// NumericUpDownJitterBufferServer_ValueChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumericUpDownJitterBufferServer_ValueChanged(object sender, EventArgs e)
        {
            m_Config.JitterBufferCountServer = (uint)NumericUpDownJitterBufferServer.Value;
        }
        /// <summary>
        /// NumericUpDownJitterBufferClient_ValueChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NumericUpDownJitterBufferClient_ValueChanged(object sender, EventArgs e)
        {
            m_Config.JitterBufferCountClient = (uint)NumericUpDownJitterBufferClient.Value;
        }
        /// <summary>
        /// StartStreamSounddevice_Client
        /// </summary>
        private void StartStreamSounddevice_Client()
        {
            StartRecordingFromSounddevice_Client();
        }
        /// <summary>
        /// StopStreamSounddevice_Client
        /// </summary>
        private void StopStreamSounddevice_Client()
        {
            StopRecordingFromSounddevice_Client();
        }
        /// <summary>
        /// IsPlayingToSoundDeviceWanted
        /// </summary>
        private bool IsPlayingToSoundDeviceWanted
        {
            get
            {
                if (ComboboxOutputSoundDeviceNameClient.SelectedIndex >= 1)
                {
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// StartPlayingToSounddevice_Client
        /// </summary>
        private void StartPlayingToSounddevice_Client()
        {
            //Wenn gewünscht
            if (IsPlayingToSoundDeviceWanted)
            {
                //JitterBuffer starten
                if (m_JitterBufferClientPlaying != null)
                {
                    InitJitterBufferClientPlaying();
                    m_JitterBufferClientPlaying.Start();
                }

                if (m_PlayerClient == null)
                {
                    m_PlayerClient = new WinSound.Player();
                    m_PlayerClient.Open(m_Config.SoundOutputDeviceNameClient, m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient, (int)m_Config.JitterBufferCountClient);
                }

                //Timer starten
                m_TimerProgressBarPlayingClient.Start();

            }

            //Anzeigen
            ComboboxOutputSoundDeviceNameClient.Invoke(new MethodInvoker(delegate()
            {
                ComboboxOutputSoundDeviceNameClient.Enabled = false;
                NumericUpDownJitterBufferClient.Enabled = false;
                //ProgressBarPlayingClient.Maximum = (int)m_JitterBufferClientPlaying.Maximum;
            }));

        }
        /// <summary>
        /// StopPlayingToSounddevice_Client
        /// </summary>
        private void StopPlayingToSounddevice_Client()
        {
            if (m_PlayerClient != null)
            {
                m_PlayerClient.Close();
                m_PlayerClient = null;
            }

            //JitterBuffer beenden
            if (m_JitterBufferClientPlaying != null)
            {
                m_JitterBufferClientPlaying.Stop();
            }

            //Timer beenden
            m_TimerProgressBarPlayingClient.Stop();

            //Anzeigen
            this.Invoke(new MethodInvoker(delegate()
            {
                ComboboxOutputSoundDeviceNameClient.Enabled = true;
                NumericUpDownJitterBufferClient.Enabled = true;
                ProgressBarPlayingClient.Value = 0;
            }));
        }
        /// <summary>
        /// ButtonServerSpeak_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonServerSpeak_Click(object sender, EventArgs e)
        {
            //Toggeln
            m_Config.ServerNoSpeakAll = !m_Config.ServerNoSpeakAll;

            //Je nach Zustand
            if (m_Config.ServerNoSpeakAll)
            {
                StopRecordingFromSounddevice_Server();
            }
            else
            {
                StartRecordingFromSounddevice_Server();
            }

            //Anzeigen
            ShowButtonServerSpeak();
        }
        /// <summary>
        /// ShowButtonServerSpeak
        /// </summary>
        private void ShowButtonServerSpeak()
        {
            if (m_Config.ServerNoSpeakAll)
            {
                ButtonServerSpeak.Image = Properties.Resources.Speak_Off;
            }
            else
            {
                ButtonServerSpeak.Image = Properties.Resources.Speak_On;
            }
        }
        /// <summary>
        /// ShowButtonClientSpeak
        /// </summary>
        private void ShowButtonClientSpeak()
        {
            if (m_Config.ClientNoSpeakAll)
            {
                ButtonClientSpeak.Image = Properties.Resources.Speak_Off;
            }
            else
            {
                ButtonClientSpeak.Image = Properties.Resources.Speak_On;
            }
        }
        /// <summary>
        /// ButtonClientListen_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonClientListen_Click(object sender, EventArgs e)
        {
            //Toggeln
            m_Config.MuteClientPlaying = !m_Config.MuteClientPlaying;
            //Anzeigen
            ShowButtonClientListen();
        }
        /// <summary>
        /// ShowButtonServerSpeak
        /// </summary>
        private void ShowButtonClientListen()
        {
            if (m_Config.MuteClientPlaying)
            {
                ButtonClientListen.Image = Properties.Resources.Listen_Off;
            }
            else
            {
                ButtonClientListen.Image = Properties.Resources.Listen_On;
            }
        }
        /// <summary>
        /// ButtonServerListen_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonServerListen_Click(object sender, EventArgs e)
        {
            //Toggeln
            m_Config.MuteServerListen = !m_Config.MuteServerListen;

            //Anzeigen
            ShowButtonServerListen();
        }
        /// <summary>
        /// ShowButtonServerListen
        /// </summary>
        private void ShowButtonServerListen()
        {
            if (m_Config.MuteServerListen)
            {
                ButtonServerListen.Image = Properties.Resources.Listen_Off;
            }
            else
            {
                ButtonServerListen.Image = Properties.Resources.Listen_On;
            }

            //Speichern
            ServerThreadData.IsMuteAll = m_Config.MuteServerListen;
        }
        /// <summary>
        /// ButtonClientSpeak_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonClientSpeak_Click(object sender, EventArgs e)
        {
            try
            {
                //Toggeln
                m_Config.ClientNoSpeakAll = !m_Config.ClientNoSpeakAll;
                //Anzeigen
                ShowButtonClientSpeak();
            }
            catch (Exception ex)
            {
                ShowError(LabelClient, ex.Message);
            }
        }

        #region 点对点通话
        private bool m_IsRunning = false;
        private bool m_IsSendingMic = false;
        private UdpServer m_pUdpServer = null;
        private IPEndPoint m_pTargetEP = null;
        private WaveIn m_pWaveIn = null;
        private WaveOut m_pWaveOut = null;
        /// <summary>
        /// 呼叫端的IP
        /// </summary>
        public string CallerIP = String.Empty;
        public int CallType = 0;
        private static string Udp_AudioPort = System.Configuration.ConfigurationManager.AppSettings["Udp_AudioPort"];
        private static int m_Codec = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["G711_a_law"]);
        private static int WavInDevice_idx = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WavInDevice"]);
        private static int WavOutDevice_idx = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WavOutDevice"]);
        public WBMsgAudioCall msgAudioCall;

        /// <summary>
        /// 初始UDP通话
        /// </summary>
        private void InitUdpCall()
        {
            if (m_pUdpServer != null)
            {
                m_pUdpServer.Dispose();
                m_pUdpServer = null;
            }

            if (m_pWaveOut != null)
            {
                m_pWaveOut.Dispose();
                m_pWaveOut = null;
            }

            m_IsRunning = true;

            //选用设备中的第一种设备做为驱动
            m_pWaveOut = new WaveOut(WaveOut.Devices[WavOutDevice_idx], 8000, 16, 1);

            m_pUdpServer = new UdpServer();
            m_pUdpServer.Bindings = new IPEndPoint[] { new IPEndPoint(IPAddress.Parse(Audio_serverIP), Convert.ToInt32(Udp_AudioPort)) };
            m_pUdpServer.PacketReceived += new PacketReceivedHandler(m_pUdpServer_PacketReceived);
            m_pUdpServer.Start();
        }

        /// <summary>
        /// 这个方法是我们得到UDP传来的声音后，进行声音播放
        /// </summary>
        /// <param name="e">Event data.</param>
        private void m_pUdpServer_PacketReceived(UdpPacket_eArgs e)
        {
            // Decompress data.
            byte[] decodedData = null;
            if (m_Codec == 0)
            {
                decodedData = G711.Decode_aLaw(e.Data, 0, e.Data.Length);
            }
            else if (m_Codec == 1)
            {
                decodedData = G711.Decode_uLaw(e.Data, 0, e.Data.Length);
            }

            // We just play received packet.
            m_pWaveOut.Play(decodedData, 0, decodedData.Length);

        }

        /// <summary>
        /// 当录音缓冲区满时，我们需要传递出去
        /// </summary>
        /// <param name="buffer">Recorded data.</param>
        private void m_pWaveIn_BufferFull(byte[] buffer)
        {
            // Compress data. 
            byte[] encodedData = null;
            if (m_Codec == 0)
            {
                encodedData = G711.Encode_aLaw(buffer, 0, buffer.Length);
            }
            else if (m_Codec == 1)
            {
                encodedData = G711.Encode_uLaw(buffer, 0, buffer.Length);
            }

            // We just sent buffer to target end point.
            m_pUdpServer.SendPacket(encodedData, 0, encodedData.Length, m_pTargetEP);
        }

        /// <summary>
        /// 关闭声音录入
        /// </summary>
        private void CloseWaveIn()
        {
            m_IsSendingMic = false;
            if (m_pWaveIn != null)
            {
                m_pWaveIn.Dispose();
                m_pWaveIn = null;
            }
        }
        /// <summary>
        /// 验证IP是否在线
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool VaildIP(string ip)
        {
            Ping pingSender = new Ping();
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1000;
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            PingReply reply = pingSender.Send(ip, timeout, buffer, options);
            return reply.Status == IPStatus.Success;
        }

        //private void OnTimerDrawServerClientsProgressBars(Object obj, EventArgs e)
        //{
        //    if (this.m_TimerDrawProgressBar.Interval % 2 == 0)
        //    {
        //        this.button2.ForeColor = System.Drawing.Color.Red;
        //    }
        //    else
        //    {
        //        this.button2.ForeColor = System.Drawing.Color.Green;
        //    }
        //    m_TimerDrawProgressBar.Interval++;
        //}

        private void ChangeText()
        {
            //if (m_TimerDrawProgressBar != null)
            //{
            //    m_TimerDrawProgressBar.Dispose();
            //    m_TimerDrawProgressBar = null;
            //}
            //m_TimerDrawProgressBar = new System.Windows.Forms.Timer();
            //m_TimerDrawProgressBar.Tick += new EventHandler(OnTimerDrawServerClientsProgressBars);
            //m_TimerDrawProgressBar.Interval = 100;
            //m_TimerDrawProgressBar.Start();
        }

        #region 通讯的交互控制
        private void HideOtherCallBtn(string ip)
        {
            TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
            for (int i = 0; i < TbPanl.Controls.Count; i++)
            {
                if (TbPanl.Controls[i] is Button)
                {
                    Button btnTmp = (Button)TbPanl.Controls[i];
                    if (!btnTmp.Name.Contains(ip))
                    {
                        btnTmp.Enabled = false;
                    }
                }
            }
        }
        private void ShowOtherCallBtn(string ip)
        {
            TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
            for (int i = 0; i < TbPanl.Controls.Count; i++)
            {
                if (TbPanl.Controls[i] is Button)
                {
                    Button btnTmp = (Button)TbPanl.Controls[i];
                    if (!btnTmp.Name.Contains(ip) && !btnTmp.Name.Contains("CallOut"))
                    {
                        btnTmp.Enabled = true;
                    }
                }
            }
        }
        public bool BeginCallIp(object sender, string targetIP)
        {
            Button btnCaller = (Button)sender;
            bool reValue = true;

            //改变字体，让它进入等待状态

            //向目标机器发送消息，如果不成功，那么则中断字体显示
            if (VaildIP(targetIP))
            {
                HideOtherCallBtn(targetIP);
                ChangeText();
                btnCaller.Text = "等待中......";
                aduio_client_netWork = new NetworkManager
                                         (
                                         this, targetIP, Audio_serverPort,
                                       SOKET_TYPE.enClientMode
                                         );
                aduio_client_netWork.ConnectToListeningServer();
                msgAudioCall = new WBMsgAudioCall();
                msgAudioCall.callType = 1;
                msgAudioCall.TargetIP = Audio_serverIP;
                aduio_client_netWork.SendWBMsgConnectedHdlr(msgAudioCall);
            }
            else
            {
                return false;
            }
            try
            {
                m_pTargetEP = new IPEndPoint(IPAddress.Parse(targetIP), Convert.ToInt32(Udp_AudioPort));
            }
            catch
            {
                MessageBox.Show(this, "Invalid target IP address or port !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            //呼叫端需要将标志设置为等待回连后的状态,同时如果在该状态点击按钮，那么将关闭通话
            CallType = 2;
            return true;
        }
        /// <summary>
        /// 用来处理接收到呼叫端的信息
        /// </summary>
        /// <param name="CallerIP">呼叫端的IP</param>
        public void WaitForCall(string CallerIP)
        {
            this.Invoke(new MethodInvoker(delegate()
            {
                TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
                for (int i = 0; i < TbPanl.Controls.Count; i++)
                {
                    Button btnTmp = (Button)TbPanl.Controls[i];
                    if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallOut"))
                    {
                        btnTmp.Enabled = true;
                    }
                    if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallIn"))
                    {
                        btnTmp.Enabled = true;
                        btnTmp.Text = "接听";
                    }
                }
                //this.button2.Text = "接听";
                //this.button3.Text = "取消";
                //this.button3.Visible = true;
                this.CallerIP = CallerIP;
                //被呼叫端需要将状态设置为等待接听状态
                this.CallType = 1;
                if (m_TimerDrawProgressBar != null)
                {
                    m_TimerDrawProgressBar.Dispose();
                    m_TimerDrawProgressBar = null;
                }
                m_TimerDrawProgressBar = new System.Windows.Forms.Timer();
                //m_TimerDrawProgressBar.Tick += new EventHandler(OnTimerDrawServerClientsProgressBars);
                m_TimerDrawProgressBar.Interval = 100;
                m_TimerDrawProgressBar.Start();
                try
                {
                    //被呼叫端与呼叫端进行UDP连接
                    m_pTargetEP = new IPEndPoint(IPAddress.Parse(this.CallerIP), Convert.ToInt32(Udp_AudioPort));
                }
                catch
                {
                    MessageBox.Show(this, "Invalid target IP address or port !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            ));
        }

        public void BCall()
        {
            this.Invoke(new MethodInvoker(delegate()
            {
                TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
                for (int i = 0; i < TbPanl.Controls.Count; i++)
                {
                    Button btnTmp = (Button)TbPanl.Controls[i];
                    if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallOut"))
                    {
                        btnTmp.Enabled = false;
                    }
                    if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallIn"))
                    {
                        btnTmp.Enabled = true;
                        btnTmp.Text = "断开通话";
                    }
                }
                this.CallType = 2;
                m_IsSendingMic = true;

                m_pWaveIn = new WaveIn(WaveIn.Devices[WavInDevice_idx], 8000, 16, 1, 400);
                m_pWaveIn.BufferFull += new BufferFullHandler(m_pWaveIn_BufferFull);
                m_pWaveIn.Start();

            }
            ));
        }
        #endregion






        private void BtnPerToPer_Click(object sender, EventArgs e)
        {
            Button btnCaller = (Button)sender;
            string callerIp = btnCaller.Name.Split('|')[1];
            switch (CallType)
            {
                case 0: //未连接的时候的操作方式
                    if (m_IsSendingMic)
                    {
                        m_IsSendingMic = false;
                        CloseWaveIn();
                    }
                    else
                    {

                        if (!BeginCallIp(btnCaller, callerIp))
                        {
                            return;
                        }
                    }
                    break;
                case 1: //被呼叫端的处理方式
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
                        for (int i = 0; i < TbPanl.Controls.Count; i++)
                        {
                            Button btnTmp = (Button)TbPanl.Controls[i];
                            if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallOut"))
                            {
                                btnTmp.Enabled = false;
                            }
                            if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallIn"))
                            {
                                btnTmp.Enabled = true;
                                btnTmp.Text = "断开通话";
                            }
                        }

                        m_IsSendingMic = true;
                        //打开被呼叫端的语音输入
                        m_pWaveIn = new WaveIn(WaveIn.Devices[WavInDevice_idx], 8000, 16, 1, 400);
                        m_pWaveIn.BufferFull += new BufferFullHandler(m_pWaveIn_BufferFull);
                        m_pWaveIn.Start();

                        aduio_client_netWork = new NetworkManager
                                                 (
                                                 this, this.CallerIP, Audio_serverPort,
                                               SOKET_TYPE.enClientMode
                                                 );
                        aduio_client_netWork.ConnectToListeningServer();
                        msgAudioCall = new WBMsgAudioCall();
                        msgAudioCall.callType = 2;
                        aduio_client_netWork.SendWBMsgConnectedHdlr(msgAudioCall);
                        this.CallType = 3;
                    }
                    ));
                    break;
                case 2: //呼叫端主动关闭
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        btnCaller.Text = "呼叫";
                        //this.button3.Visible = false;
                        //关闭语音通道
                        CloseWaveIn();
                        ShowOtherCallBtn(callerIp);
                        //向目标机器发送关闭请求
                        aduio_client_netWork = new NetworkManager
                                                 (
                                                 this, callerIp, Audio_serverPort,
                                               SOKET_TYPE.enClientMode
                                                 );
                        aduio_client_netWork.ConnectToListeningServer();
                        msgAudioCall = new WBMsgAudioCall();
                        msgAudioCall.callType = 3;
                        aduio_client_netWork.SendWBMsgConnectedHdlr(msgAudioCall);
                    }
                    ));
                    break;
                case 3: //被呼叫端主动关闭
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        TableLayoutPanel TbPanl = (TableLayoutPanel)this.tabSL.Controls.Find("tabSLUsers", true)[0];
                        for (int i = 0; i < TbPanl.Controls.Count; i++)
                        {
                            Button btnTmp = (Button)TbPanl.Controls[i];
                            if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallOut"))
                            {
                                btnTmp.Enabled = false;
                            }
                            if (!btnTmp.Name.Contains(CallerIP) && !btnTmp.Name.Contains("CallIn"))
                            {
                                btnTmp.Enabled = true;
                                btnTmp.Text = "呼叫";
                            }
                        }
                        //关闭语音通道
                        CloseWaveIn();
                        //向目标机器发送关闭请求
                        aduio_client_netWork = new NetworkManager
                                                 (
                                                 this, this.CallerIP, Audio_serverPort,
                                               SOKET_TYPE.enClientMode
                                                 );
                        aduio_client_netWork.ConnectToListeningServer();
                        msgAudioCall = new WBMsgAudioCall();
                        msgAudioCall.callType = 4;
                        aduio_client_netWork.SendWBMsgConnectedHdlr(msgAudioCall);
                    }
                    ));
                    break;
            }
        }

        #endregion

        #endregion

       

       
    }
    #region 配置文件和服务器线程数据
    /// <summary>
    /// Config
    /// </summary>
    public class Configuration
    {
        /// <summary>
        /// Config
        /// </summary>
        public Configuration()
        {

        }

        //Attribute
        public String IpAddressClient = "";
        public String IPAddressServer = "";
        public int PortClient = 0;
        public int PortServer = 0;
        public String SoundInputDeviceNameClient = "";
        public String SoundOutputDeviceNameClient = "";
        public String SoundInputDeviceNameServer = "";
        public String SoundOutputDeviceNameServer = "";
        public int SamplesPerSecondClient = 8000;
        public int BitsPerSampleClient = 16;
        public int ChannelsClient = 1;
        public int SamplesPerSecondServer = 8000;
        public int BitsPerSampleServer = 16;
        public int ChannelsServer = 1;
        public bool UseJitterBufferClientRecording = true;
        public bool UseJitterBufferServerRecording = true;
        public uint JitterBufferCountServer = 20;
        public uint JitterBufferCountClient = 20;
        public string FileName = "";
        public bool LoopFile = false;
        public bool MuteClientPlaying = false;
        public bool ServerNoSpeakAll = false;
        public bool ClientNoSpeakAll = false;
        public bool MuteServerListen = false;
        public String SelfIp = "";
    }
    /// <summary>
    /// ServerThreadData
    /// </summary>
    public class ServerThreadData
    {
        /// <summary>
        /// Konstruktor
        /// </summary>
        public ServerThreadData()
        {

        }

        //Attribute
        public NF.ServerThread ServerThread;
        public WinSound.Player Player;
        public WinSound.JitterBuffer JitterBuffer;
        public WinSound.Protocol Protocol;
        public int SamplesPerSecond = 8000;
        public int BitsPerSample = 16;
        public int SoundBufferCount = 8;
        public uint JitterBufferCount = 20;
        public uint JitterBufferMilliseconds = 20;
        public int Channels = 1;
        private bool IsInitialized = false;
        public bool IsMute = false;
        public static bool IsMuteAll = false;

        /// <summary>
        /// Init
        /// </summary>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        public void Init(NF.ServerThread st, string soundDeviceName, int samplesPerSecond, int bitsPerSample, int channels, int soundBufferCount, uint jitterBufferCount, uint jitterBufferMilliseconds)
        {
            //Werte übernehmen
            this.ServerThread = st;
            this.SamplesPerSecond = samplesPerSecond;
            this.BitsPerSample = bitsPerSample;
            this.Channels = channels;
            this.SoundBufferCount = soundBufferCount;
            this.JitterBufferCount = jitterBufferCount;
            this.JitterBufferMilliseconds = jitterBufferMilliseconds;

            //Player
            this.Player = new WinSound.Player();
            this.Player.Open(soundDeviceName, samplesPerSecond, bitsPerSample, channels, soundBufferCount);

            //Wenn ein JitterBuffer verwendet werden soll
            if (jitterBufferCount >= 2)
            {
                //Neuen JitterBuffer erstellen
                this.JitterBuffer = new WinSound.JitterBuffer(this.Player, jitterBufferCount, jitterBufferMilliseconds);
                this.JitterBuffer.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferDataAvailable);
                this.JitterBuffer.Start();
            }

            //Protocol
            this.Protocol = new WinSound.Protocol(WinSound.ProtocolTypes.LH, Encoding.Default);
            this.Protocol.DataComplete += new WinSound.Protocol.DelegateDataComplete(OnProtocolDataComplete);


            //Initialisiert
            IsInitialized = true;
        }
        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            //Protocol
            if (Protocol != null)
            {
                this.Protocol.DataComplete -= new WinSound.Protocol.DelegateDataComplete(OnProtocolDataComplete);
                this.Protocol = null;
            }

            //JitterBuffer
            if (JitterBuffer != null)
            {
                JitterBuffer.Stop();
                JitterBuffer.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferDataAvailable);
                this.JitterBuffer = null;
            }

            //Player
            if (Player != null)
            {
                Player.Close();
                this.Player = null;
            }

            //Nicht initialisiert
            IsInitialized = false;
        }
        /// <summary>
        /// OnProtocolDataComplete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void OnProtocolDataComplete(Object sender, Byte[] bytes)
        {
            //Wenn initialisiert
            if (IsInitialized)
            {
                if (ServerThread != null && Player != null)
                {
                    try
                    {
                        //Wenn der Player gestartet wurde
                        if (Player.Opened)
                        {

                            //RTP Header auslesen
                            WinSound.RTPPacket rtp = new WinSound.RTPPacket(bytes);

                            //Wenn Header korrekt
                            if (rtp.Data != null)
                            {
                                //Wenn JitterBuffer verwendet werden soll
                                if (JitterBuffer != null && JitterBuffer.Maximum >= 2)
                                {
                                    JitterBuffer.AddData(rtp);
                                }
                                else
                                {
                                    //Wenn kein Mute
                                    if (IsMuteAll == false && IsMute == false)
                                    {
                                        //Nach Linear umwandeln
                                        Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, this.BitsPerSample, this.Channels);
                                        //Abspielen
                                        Player.PlayData(linearBytes, false);
                                    }
                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        IsInitialized = false;
                    }
                }
            }
        }
        /// <summary>
        /// OnJitterBufferDataAvailable
        /// </summary>
        /// <param name="packet"></param>
        private void OnJitterBufferDataAvailable(Object sender, WinSound.RTPPacket rtp)
        {
            if (Player != null)
            {
                //Wenn kein Mute
                if (IsMuteAll == false && IsMute == false)
                {
                    //Nach Linear umwandeln
                    Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, BitsPerSample, Channels);
                    //Abspielen
                    Player.PlayData(linearBytes, false);
                }
            }
        }
    }
    #endregion
}
